271

I have this PHP code:

function ShowFileExtension($filepath)
{
 preg_match('/[^?]*/', $filepath, $matches);
 $string = $matches[0];
 $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
 if(count($pattern) > 1)
 {
 $filenamepart = $pattern[count($pattern)-1][0];
 preg_match('/[^?]*/', $filenamepart, $matches);
 return strtolower($matches[0]);
 }
}

If I have a file named my.zip, this function returns .zip.

I want to do the reverse, I want the function to return my without the extension.

The file is just a string in a variable.

Dharman
34k27 gold badges105 silver badges156 bronze badges
asked Feb 2, 2010 at 11:10
0

17 Answers 17

529

No need for all that. Check out pathinfo(), it gives you all the components of your path.

$filename = pathinfo($filepath, PATHINFO_FILENAME);

will give you the filename without extension.

Some other examples from the manual:

$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0

Output of the code:

/www/htdocs
index.html
html
index

And alternatively you can get only certain parts like:

echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
Your Common Sense
158k42 gold badges226 silver badges374 bronze badges
answered Feb 2, 2010 at 11:13
Sign up to request clarification or add additional context in comments.

5 Comments

Why was this downvoted? The answer is absolutely correct. pathinfo operates on strings, so it doesn't matter if the file is actually on the server or not.
It's unfortunate that they misnamed "basename", since it returns the full filename with extension, not the base name.
@Oscar it is the most widely understood meaning of the term basename. No misnaming.
This is very useful, especially when you don't need to know the file extension in order to extract it.
Be aware that this will provide wrong information with multiple dot extensions like .tar.gz
224

As an alternative to pathinfo(), you can use

  • basename() — Returns filename component of path

Example from PHP manual

$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"

You have to know the extension to remove it in advance though.

However, since your question suggests you have the need for getting the extension and the basename, I'd vote Pekka's answer as the most useful one, because it will give you any info you'd want about the path and file with one single native function.

answered Feb 2, 2010 at 11:13

2 Comments

what if i do not know about file extension .. let say if path is dynamic anytype of file extension can come in it !! then what ??
@user889030 then you have a different scenario than the OP and don't use basename, but pathinfo as shown elsewere on the page.
134

https://php.net/manual/en/function.pathinfo.php

pathinfo($path, PATHINFO_FILENAME);

Simple functional test: https://ideone.com/POhIDC

answered Sep 26, 2013 at 23:20

1 Comment

Whoever decided that filename doesn't have an extension while basename does must have some sadistic tendencies...
19

Another approach is by using regular expressions.

$fileName = basename($filePath);
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $fileName);

This removes from the last period . up until the end of the string.

answered Mar 21, 2014 at 2:13

6 Comments

Much better than using explode, and only catches the last period section in case you used periods in file names
No, it's much much worse. Stop regexing people.
Thanks, and the above comments nailed it. Not having to know the extension makes this more useful.
@caiosm1005, The attack surface immediately increases because It's hard to reason against the internals of a regex engine. For example, in the code above, it wouldn't be odd if there's some input $fileName which could cause the engine to run in exponential (or worse) time. And assuming we have finished dissecting the internals of this specific regex engine and have theoretically proven it to be robust against every possible value $fileName could be, the code is still not arbitrarily portable to another platform that has another implementation of the regex engine.
@Pacerier I have to disagree. Firstly, this is a very simple regex; I just can't see how the processing time could increase exponentially. Secondly, there are no special wildcards in this expression, so it should be able to run the same in any regex implementation.
|
15

If the extension is not known, use this solution

 pathinfo('D:/dir1/dir2/fname', PATHINFO_FILENAME); // return "fname"
 pathinfo('D:/dir1/dir2/fname.php', PATHINFO_FILENAME); // return "fname"
 pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "fname"
 pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_DIRNAME) . '/' . pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "D:/dir1/dir2/fname"

PHP MAN function pathinfo

yckart
33.6k11 gold badges126 silver badges133 bronze badges
answered Jun 4, 2015 at 13:18

3 Comments

Please provide a like to the php man page for pathinfo. This is going to help OP make the ShowFileExtension method better and will provide extra reading for anyone trying to find this answer. Also a bit of a description would not go astray...
I have answered this question already with the same solution, ~2 years before yours ;)
@yckart true but this does give multiple examples within the answer. Yours has the benefit of linking to ideone.com but the site could go offline.
8

Almost all the above solution have the shown getting filename from variable $path

Below snippet will get the current executed file name without extension

echo pathinfo(basename($_SERVER['SCRIPT_NAME']), PATHINFO_FILENAME);

Explanation

$_SERVER['SCRIPT_NAME'] contains the path of the current script.

answered Jan 27, 2017 at 12:56

Comments

6

@Gordon basename will work fine if you know the extension, if you dont you can use explode:

$filename = end(explode(".", $file));
answered Feb 2, 2010 at 11:25

2 Comments

Please direct comments to me with the comment function below my answer. The most appropriate function for this is pathinfo, which is why I gave basename as an alternative only. There is no need to reinvent pathinfo with regex or explode.
@fire, Your update makes no sense. end(explode(".", $file)); gives you the extension, not the filename.
4

@fire incase the filename uses dots, you could get the wrong output. I would use @Gordon method but get the extension too, so the basename function works with all extensions, like this:

$path = "/home/httpd/html/index.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);
$file = basename($path, ".".$ext); // $file is set to "index"
answered May 2, 2013 at 12:15

Comments

3

in my case, i use below. I don't care what is its extention. :D i think it will help you

$exploded_filepath = explode(".", $filepath_or_URL);
$extension = end($exploded_filepath);
echo basename($filepath_or_URL, ".".$extension ); //will print out the the name without extension.
AlbinoDrought
1,52623 silver badges29 bronze badges
answered Jul 26, 2015 at 21:37

1 Comment

Btw.: You have a typo in $extenion
2

Short

echo pathinfo(__FILE__)['filename']; // since php 5.2
answered Dec 28, 2015 at 12:35

2 Comments

good. But if i put above code in b.php and i executed a.php having require('b.php'). Then output will how b instead of a
almost there : echo pathinfo($filename_with_extension)['filename'];
2

Sometimes an extension contains more than one part. It may or may not be desirable to remove the entire extension. The function below removes the entire extension if you pass true as the second parameter:

function removeExt($path, $fullExt = false)
{
 if ($fullExt === false)
 return pathinfo($path, PATHINFO_FILENAME);
 $basename = basename($path);
 return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}

Eg:

echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file.tar
echo removeExt('https://example.com/file.tar.gz', true);
// https://example.com/file
echo removeExt('file.tar.gz');
// file.tar
echo removeExt('file.tar.gz', true);
// file
echo removeExt('file');
// file
answered Aug 5, 2018 at 15:21

4 Comments

Better to use strripos instead of stripos, to avoide dots in file name.
@KhalidAlmannai Using strripos would fail to remove the full extension. It would remove .gz, instead of .tar.gz. In some cases it maybe desirable to only remove the last part of the extension but not always.
Yes, that's true.
@KhalidAlmannai I've updated my answer to allow for either removing part of the extension or the full extension, based on an optional parameter.
1

File name without file extension when you don't know that extension:

$basename = substr($filename, 0, strrpos($filename, "."));

answered Aug 27, 2014 at 7:37

1 Comment

How about if the extension is something like .tar.gz ?
1

If you don't know which extension you have, then you can try this:

$ext = strtolower(substr('yourFileName.ext', strrpos('yourFileName.ext', '.') + 1));
echo basename('yourFileName.ext','.'.$ext); // output: "youFileName" only

Working with all possibilities:

image.jpg // output: "image"
filename.image.png // output: "filename.image"
index.php // output: "index"
answered Jun 25, 2015 at 17:53

Comments

1

You can write this

$filename = current(explode(".", $file));

These will return current element of array, if not used before.

answered Oct 6, 2015 at 11:59

2 Comments

Hello, Pleas e check before downgrading it. It is working I had used it in my code many a times. By using this function you can get just a file name If you file name is "xyz.jpg". It may not work with file names containing entire path in it.
This also doesn't work correctly if a filename has multiple dots in it, e.g. "some.interesting.image.jpg"
0

This return only filename without any extension in 1 row:

$path = "/etc/sudoers.php"; 
print array_shift(explode(".", basename($path)));
// will print "sudoers"
$file = "file_name.php"; 
print array_shift(explode(".", basename($file)));
// will print "file_name"
answered Mar 27, 2015 at 15:20

Comments

0

Your answer is below the perfect solution to hide to file extension in php.

<?php
 $path = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
 echo basename($path, ".php");
?>
answered May 21, 2016 at 13:35

Comments

-1

File extension extract from file:

File Name = subrotobiswas.jpg
$fileExtension = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION); //Output: jpg
$newNameOfFileWithoutExtension = basename( $_FILES["fileToUpload"]["name"], $fileExtension ); //Output: subrotobiswas
$fullFileName = $newNameOfFileWithoutExtension . "." .$fileExtension; // Output: subrotobiswas.jpg
answered Sep 10, 2022 at 13:22

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.