Remove file name from path php

Note that when a string contains only a filename without a path (e.g. "test.txt"), the dirname() and pathinfo() functions return a single dot (".") as a directory, instead of an empty string. And if your string ends with "/", i.e. when a string contains only path without filename, these functions ignore this ending slash and return you a parent directory. In some cases this may be undesirable behavior and you need to use something else. For example, if your path may contain only forward slashes "/", i.e. only one variant (not both slash "/" and backslash "\") then you can use this function:

function stripFileName(string $path): string
{
    if (($pos = strrpos($path, '/')) !== false) {
        return substr($path, 0, $pos);
    } else {
        return '';
    }
}

Or the same thing little shorter, but less clear:

function stripFileName(string $path): string
{
    return substr($path, 0, (int) strrpos($path, '/'));
}

Removing the file path from a filename in PHP is be easy!

The basename() function will remove the file’s path from your string and leave only the filename. So, for example, it means that if your file path string is: ‘/home/anto.online/apac/basepath/test.php’, then using basename($path) will return only the filename. The result will thus be: ‘test.php’.

Functions used in conjunction

The basename() function is often used with these PHP functions:

realpath() – Returns the full absolute path, including the filename.

dirname() – Can return the file path of a parent directory. If there are no slashes in the file path, a dot (‘.‘) is returned, indicating the current file path. Otherwise, the returned string is a file path with any trailing component removed.

Example of how to use these functions in PHP:

//get the absolute path of a file
$real = realpath('./test.php');
echo 'realpath result: ' . $real . '
'; //output: /home/anto.online/apac/basepath/test.php //get the absolute path of a file $dir = dirname('./test.php'); echo 'dirname result: ' . $dir . '
'; //output: . //get the filename and remove the filepath $base = basename($real); echo 'basename result: ' . $base . '
'; //output: test.php

Practical example – Removing file path from error message

Let’s say you need to write an error handler in PHP. The custom handler must not expose paths to the front-end. Your remove file paths for security reasons.

We can use basepath() to sanitize the $file variable and remove file paths.

Thus, for the custom error handler example below:

function customErrorHandler($code, $message, $file, $line) {
$logger = createLogger();
...

We can do this by determining the string position of the ‘/’ and then use a  substring function. (This would be the hard way!)

Alternatively, we can use the basename() method in PHP. It even considers the differences between Windows and Linux!

Adding the basename() function will make our error handler look like this:

function customErrorHandler($code, $message, $file, $line) {
$logger = createLogger();
...
$message = 'Error ID: [' . $uid . '] [' . SITE_ID . '] ' . $user . 'Message: [' . $message . '] At: [' . basename($file) . '] Line: [' . $line . '] Code: [' . $code . ']';
...

You may also be interested in



About the Authors

Anto's editorial team loves the cloud as much as you! Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic! Contact Anto Online if you want to contribute.

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee



(PHP 4, PHP 5, PHP 7, PHP 8)

basenameReturns trailing name component of path

Description

basename(string $path, string $suffix = ""): string

Note:

basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Caution

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. If path contains characters which are invalid for the current locale, the behavior of basename() is undefined.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

suffix

If the name component ends in suffix this will also be cut off.

Return Values

Returns the base name of the given path.

Examples

Example #1 basename() example

echo "1) ".basename("/etc/sudoers.d"".d").PHP_EOL;
echo 
"2) ".basename("/etc/sudoers.d").PHP_EOL;
echo 
"3) ".basename("/etc/passwd").PHP_EOL;
echo 
"4) ".basename("/etc/").PHP_EOL;
echo 
"5) ".basename(".").PHP_EOL;
echo 
"6) ".basename("/");
?>

The above example will output:

1) sudoers
2) sudoers.d
3) passwd
4) etc
5) .
6) 

See Also

  • dirname() - Returns a parent directory's path
  • pathinfo() - Returns information about a file path

Anonymous

5 years ago

It's a shame, that for a 20 years of development we don't have mb_basename() yet!

// works both in windows and unix
function mb_basename($path) {
    if (preg_match('@^.*[\\\\/]([^\\\\/]+)$@s', $path, $matches)) {
        return $matches[1];
    } else if (preg_match('@^([^\\\\/]+)$@s', $path, $matches)) {
        return $matches[1];
    }
    return '';
}

stephane dot fidanza at gmail dot com

15 years ago

Support of the $suffix parameter has changed between PHP4 and PHP5:
in PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.

Example:
  $file = "path/to/file.xml#xpointer(/Texture)";
  echo
basename($file, ".xml#xpointer(/Texture)");
?>

Result in PHP4: file
Result in PHP5: Texture)

swedish boy

12 years ago

Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

// your file
$file = 'image.jpg';$info = pathinfo($file);
$file_name basename($file,'.'.$info['extension']);

echo

$file_name; // outputs 'image'?>

zandor_zz at yahoo dot it

14 years ago

It might be useful to have a version of the function basename working with arrays too.

function a_basename( $file, $exts )
{
   
$onlyfilename = end( explode( "/", $file ) );

    if(

is_string( $exts ) )
    {
        if (
strpos( $onlyfilename, $exts, 0 ) !== false )
       
$onlyfilename = str_replace( $exts, "", $onlyfilename );
    }
    else if (
is_array( $exts ) )
    {
       
// works with PHP version <= 5.x.x
       
foreach( $exts as $KEY => $ext )
        {
           
$onlyfilename = str_replace( $ext, "", $onlyfilename );
        }
    }

    return

$onlyfilename ;
}
?>

lazy lester

16 years ago

If your path has a query string appended, and if the query string contains a "/" character, then the suggestions for extracting the filename offered below don't work.

For instance if the path is like this:
http://www.ex.com/getdat.php?dep=n/a&title=boss

Then both the php basename() function, and also
the $_SERVER[QUERY_STRING] variables get confused.

In such a case, use:

$path_with_query="http://www.ex.com/getdat.php?dep=n/a&title=boss";
$path=explode("?",$path_with_query);
$filename=basename($path[0]);
$query=$path[1];
?>

pvollma at pcvsoftware dot net

17 years ago

There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):

$newfile = basename($filen);
if (
strpos($newfile,'\\') !== false) {
 
$tmp = preg_split("[\\\]",$newfile);
 
$newfile = $tmp[count($tmp) - 1];
}
?>

$newfile will now contain only the file name and extension, even if the POSTed file name included a full Windows path.

KOmaSHOOTER at gmx dot de

17 years ago

If you want the current path where youre file is and not the full path then use this :)

echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));   
// retuns the name of current used directory
?>

Example:

www dir: domain.com/temp/2005/january/t1.php

echo('dirname
'
.dirname($_SERVER['PHP_SELF']).'

'
);   
// returns: /temp/2005/january
?>

echo('file = '.basename ($PHP_SELF,".php"));   
// returns: t1
?>

if you combine these two you get this
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));   
// returns: january
?>

And for the full path use this
echo(' PHP_SELF
'
.$_SERVER['PHP_SELF'].'

'
);
// returns: /temp/2005/january/t1.php   
?>

KOmaSHOOTER at gmx dot de

18 years ago

Exmaple for exploding ;) the filename to an array

echo(basename ($PHP_SELF)."
"
);  // returnes filename.php
$file = basename ($PHP_SELF);
$file = explode(".",$file);
print_r($file);    // returnes Array ( [0] => filename [1] => php )
echo("
"
);
$filename = basename(strval($file[0]),$file[1]);
echo(
$filename."
"
);  // returnes  filename
echo(basename ($PHP_SELF,".php")."
"
);  // returnes  filename
echo("
"
);
echo(
"
"
);
//show_source(basename ($PHP_SELF,".php").".php")
show_source($file[0].".".$file[1])
?>

Anonymous

5 years ago

There is a problem reading non-Latin characters in the file name if the locale is not configured correctly.
For example: instead of the name «ФЫВА-1234.doc», is displayed «-1234.doc».
Solution: rawurldecode(basename($full_name)).

stocki dot r at gmail dot com

3 years ago

Additional note to Anonymous's mb_basename() solution: get rid of trailing slashes/backslashes!

function mb_basename($path) {
    if (
preg_match('@^.*[\\\\/]([^\\\\/]+)([\\\\/]+)?$@s', $path, $matches)) {
        return
$matches[1];
    } else if (
preg_match('@^([^\\\\/]+)([\\\\/]+)?$@s', $path, $matches)) {
        return
$matches[1];
    }
    return
'';
}

echo

mb_basename("/etc//"); # "etc"
?>

crash at subsection dot org dot uk

16 years ago

A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

since basename always treats a path as a path to a file, e.g.

/var/www/site/foo/ indicates /var/www/site as the path to file
foo

poop at poop dot com

7 years ago

@ lcvalentine at gmail dot com
>This is much simpler:
>$ext = strrchr( $filename, '.' );

Even though yours is shorter, you can also do:

$ext = end(explode(".", basename($file

amitabh at NOSPAM dot saysnetsoft dot com

17 years ago

The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
function GetFileName($file_name)
{
       
$newfile = basename($file_name);
        if (
strpos($newfile,'\\') !== false)
        {
               
$tmp = preg_split("[\\\]",$newfile);
               
$newfile = $tmp[count($tmp) - 1];
                return(
$newfile);
        }
        else
        {
                return(
$file_name);
        }
}
?>

Muhammad El-Saeed muhammad at elsaeed dot info

9 years ago

to get the base url of my website

function url(){
    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://'. $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); 
    return $base_url;
}

adrian at foeder dot de

14 years ago

On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:

//assume the real filename is mytest.JPG:$name_i_have = "mytest.jpg";
$realfilename = basename(realpath($name_i_have));
?>

basename itself does not check the filesystem for the given file, it does, so it seems, only string-manipulation.
With realpath() you can "extend" this functionality.

pai dot ravi at yahoo dot com

14 years ago

once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:

function splitFilename($filename)
{
   
$pos = strrpos($filename, '.');
    if (
$pos === false)
    {
// dot is not found in the filename
       
return array($filename, ''); // no extension
   
}
    else
    {
       
$basename = substr($filename, 0, $pos);
       
$extension = substr($filename, $pos+1);
        return array(
$basename, $extension);
    }
}
?>

hello at haroonahmad dot co dot uk

13 years ago

I got a blank output from this code

$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

suggested earlier by a friend here.

So anybody who wants to get the current directory path can use another technique that I use as

//suppose you're using this in pageitself.php page

$current_dir=dirname(realpath("pageitself.php"));

I hope it helps.

Anonymous

7 years ago

As already pointed out above, if a query string contains a '/' character, basename will not handle it well. But it can come really handy when you want to pass a url with query string to a funtion that copies/downloads the file using basename as local filename, by attaching  an extra query to the end of the url:

  $url = 'http://example.com/url?with=query_string';
 
basename($url); // url?with=query_string
 
$url = $url . '&filename_for_basename=/desired_filename.ext';
 
basename($url); // desired_filename.ext
?>

Note: you can use the filename from the HTTP header (if present) to get the file with it's original filename.

icewind

16 years ago

Because of filename() gets "file.php?var=foo", i use explode in addition to basename like here:

$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$file = $file[0];
$query = $file[1];

Now $file only contains "file.php" and $query contains the query-string (in this case "var=foo").

www.turigeza.com

16 years ago

simple but not said in the above examples

echo basename('somewhere.com/filename.php?id=2', '.php');
will output
filename.php?id=2

which is not the filename in case you expect!

gandung at ppp dot cylab dot cmu dot edu

5 years ago

My opinion is, remove the $suffix first, and then apply splitting the core basename ( PHP 4 ):

/*
* From :
*
* PHP 4: $suffix is removed first, and then the core basename is applied.
* PHP 5: $suffix is removed after applying the core basename.
*
* (c) Paulus Gandung Prakosa ()
*/
if ( !function_exists('php4_backward_compat_basename') )
{
        function php4_backward_compat_basename($path, $suffix = '')
        {
                if ( $suffix !== '' ) {
                        $fixed_path = substr($path, 0, strlen($path) - strlen($suffix));
                        $fixed_basename = explode('/', $fixed_path);
                }

                return ( isset($fixed_basename) ? array_pop($fixed_basename) : array_pop(explode('/', $path)) );
        }
}

Anonymous

16 years ago

icewinds exmaple wouldn't work, the query part would contain the second char of the filename, not the query part of the url.
$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$query = $file[1];
$file = $file[0];
?>

That works better.

daijoubu_NOSP at M_videotron dot ca

18 years ago

An faster alternative to:

array_pop(explode('.', $fpath));
?>

would be:

substr($fpath, strrpos($fpath, '.')); // returns the dot
?>

If you don't want the dot, simply adds 1 to the position

substr($fpath, strrpos($fpath, '.') + 1); // returns the ext only
?>

KOmaSHOOTER at gmx dot de

17 years ago

if you want the name of the parent directory
$_parenDir_path = join(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1),"/").'/'; // returns the full path to the parent dir
$_parenDir basename ($_parenDir_path,"/"); // returns only the name of the parent dir
// or
$_parenDir2 = array_pop(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1)); // returns also only the name of the parent dir
echo('$_parenDir_path  = '.$_parenDir_path.'
'
);
echo(
'$_parenDir  = '.$_parenDir.'
'
);
echo(
'$_parenDir2  = '.$_parenDir2.'
'
);
?>

frank1982

5 years ago

Try Long Path Tool as it can remove any problems that you might have.

How to remove file name from path in PHP?

Removing the file path from a filename in PHP is be easy! The basename() function will remove the file's path from your string and leave only the filename. So, for example, it means that if your file path string is: '/home/anto.

How to remove file extension from filename PHP?

When an extension of file is known it can be passed as a parameter to basename function to tell it to remove that extension from the filename. echo $x ; ?> Using substr()and strrpos() function: Another way of removing an extension from a filename is using the string functions substr and strrpos.

What is __ FILE __ in PHP?

__FILE__ is simply the name of the current file. realpath(dirname(__FILE__)) gets the name of the directory that the file is in -- in essence, the directory that the app is installed in.

How do I find the root path?

In order to get the root directory path, you can use _DIR_ or dirname(). echo dirname(__FILE__); Both the above syntaxes will return the same result.