basename

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

basenameReturns trailing name component of path

Description

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

Given a string containing the path to a file or directory, this function will return the trailing name component.

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

<?php
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
add a note

User Contributed Notes 20 notes

up
51
Anonymous
7 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 '';
}
up
36
stephane dot fidanza at gmail dot com
17 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:
<?php
$file
= "path/to/file.xml#xpointer(/Texture)";
echo
basename($file, ".xml#xpointer(/Texture)");
?>

Result in PHP4: file
Result in PHP5: Texture)
up
7
zandor_zz at yahoo dot it
15 years ago
It might be useful to have a version of the function basename working with arrays too.

<?php
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 ;
}
?>
up
10
(remove) dot nasretdinov at (remove) dot gmail dot com
16 years ago
There is only one variant that works in my case for my Russian UTF-8 letters:

<?php
function mb_basename($file)
{
return
end(explode('/',$file));
}
><

It is intented for UNIX servers
up
4
KOmaSHOOTER at gmx dot de
19 years ago
If you want the current path where youre file is and not the full path then use this :)

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

Example:

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

<?php
echo('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');
// returns: /temp/2005/january
?>

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

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

And for the full path use this
<?php
echo(' PHP_SELF <br>'.$_SERVER['PHP_SELF'].'<br><br>');
// returns: /temp/2005/january/t1.php
?>
up
5
swedish boy
14 years ago
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

<?php

// your file
$file = 'image.jpg';

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

echo
$file_name; // outputs 'image'

?>
up
2
KOmaSHOOTER at gmx dot de
20 years ago
Exmaple for exploding ;) the filename to an array

<?php
echo(basename ($PHP_SELF)."<br>"); // returnes filename.php
$file = basename ($PHP_SELF);
$file = explode(".",$file);
print_r($file); // returnes Array ( [0] => filename [1] => php )
echo("<br>");
$filename = basename(strval($file[0]),$file[1]);
echo(
$filename."<br>"); // returnes filename
echo(basename ($PHP_SELF,".php")."<br>"); // returnes filename
echo("<br>");
echo(
"<br>");
//show_source(basename ($PHP_SELF,".php").".php")
show_source($file[0].".".$file[1])
?>
up
3
lazy lester
18 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:

<php
$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];
?>
up
0
hello at haroonahmad dot co dot uk
15 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.
up
0
pvollma at pcvsoftware dot net
19 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):

<?php
$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.
up
-2
Anonymous
7 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)).
up
-1
stocki dot r at gmail dot com
5 years ago
Additional note to Anonymous's mb_basename() solution: get rid of trailing slashes/backslashes!

<?php
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"
?>
up
-4
crash at subsection dot org dot uk
18 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
up
-4
pai dot ravi at yahoo dot com
16 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:

<?php
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);
}
}
?>
up
-4
Muhammad El-Saeed muhammad at elsaeed dot info
11 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;
}
up
-1
clayrabbit2 at gmail dot com
1 year ago
One line alternative for unicode filenames:
<?php

preg_replace
('#.*?([^'.DIRECTORY_SEPARATOR.']*)'.DIRECTORY_SEPARATOR.'*$#', '$1', $path);
up
-5
poop at poop dot com
9 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
up
-4
amitabh at NOSPAM dot saysnetsoft dot com
19 years ago
The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
<?php
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);
}
}
?>
up
-5
Anonymous
9 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:

<?php
$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.
up
-4
gandung at ppp dot cylab dot cmu dot edu
7 years ago
My opinion is, remove the $suffix first, and then apply splitting the core basename ( PHP 4 ):

/*
* From stephane.fidanza@gmail.com:
*
* 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 (rvn.plvhx@gmail.com)
*/
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)) );
}
}
To Top