Filesystem 函数
在线手册:中文 英文
PHP手册

basename

(PHP 4, PHP 5)

basename返回路径中的文件名部分

说明

string basename ( string $path [, string $suffix ] )

给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结束的,那这一部分也会被去掉。

在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。

Example #1 basename() 例子

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

Note:

suffix 参数是 PHP 4.1.0 新加的。

参见 dirname()


Filesystem 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 返回路径中的文件名部分

用户评论:

tamar at atarplpl dot co dot il (08-Nov-2011 10:00)

If you have problem with this function and UTF8 charset, you only have to upgrade php version to 5.2 or higher

noemail at nosite dot com (26-Feb-2010 09:00)

you could use this function when you need basename to work with cyrillic filenames

<?php
   
function pcgbasename($param, $suffix=null) {
        if (
$suffix ) {
           
$tmpstr = ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
            if ( (
strpos($param, $suffix)+strlen($suffix) )  ==  strlen($param) ) {
                return
str_ireplace( $suffix, '', $tmpstr);
            } else {
                return
ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
            }
        } else {
            return
ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
        }
    }
?>

swedish boy (12-Oct-2009 11:43)

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'

?>

leelu123 at gmail dot com (13-Apr-2009 01:45)

To get the inner most dir of a path

<?php

$DirPath
= '/var/www/fruits/apple/';

//To get the innermost dir 'apple'

$InnermostDir = basename(rtrim($DirPath, '/'));

echo
$InnermostDir; //will display 'apple'

?>

info at smaartweb dot com (23-Feb-2009 04:38)

here are two good functions to extract the filename and extension part from any given path or url.

<?php
   
function ShowFileExtension($filepath)
    {
       
preg_match('/[^?]*/', $filepath, $matches);
       
$string = $matches[0];
     
       
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);

       
# check if there is any extension
       
if(count($pattern) == 1)
        {
            echo
'No File Extension Present';
            exit;
        }
       
        if(
count($pattern) > 1)
        {
           
$filenamepart = $pattern[count($pattern)-1][0];
           
preg_match('/[^?]*/', $filenamepart, $matches);
            echo
$matches[0];
        }
    }
   
    function
ShowFileName($filepath)
    {
       
preg_match('/[^?]*/', $filepath, $matches);
       
$string = $matches[0];
       
#split the string by the literal dot in the filename
       
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
       
#get the last dot position
       
$lastdot = $pattern[count($pattern)-1][1];
       
#now extract the filename using the basename function
       
$filename = basename(substr($string, 0, $lastdot-1));
       
#return the filename part
       
return $filename;
    }
?>

usage

<?php
  
//$string = 'C:\My Documents\My Name\filename.ext';
    //$string = 'http://php.net/manual/add-note.php?
&redirect=http://php.net/function.basename.php';
   
   
echo ShowFileName($string);
    echo
ShowFileExtension($string);
?>

Joel Franusic (12-Nov-2008 11:30)

The results of the basename() function are dependent on your locale setting.

If basename() is returning blank results for strings with multibyte characters, you can try including the following in your script:

<?php

setlocale
(LC_ALL, 'en_US.UTF8'); # or any other locale that can handle multibyte characters.

?>

However, the best solution to do this would be to change the locale setting on your system or webserver. For example, on Debian systems, this is done in /etc/init.d/apache

hello at haroonahmad dot co dot uk (18-Sep-2008 04:13)

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.

zandor_zz at yahoo dot it (08-Sep-2008 09:34)

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 ;
}
?>

(remove) dot nasretdinov at (remove) dot gmail dot com (27-Aug-2008 04:20)

There is only one variant that works in my case for my Russian UTF-8 letters:

function mb_basename($file)
{
return end(explode('/',$file));
}

It is intented for UNIX servers

pai dot ravi at yahoo dot com (15-Aug-2008 04:44)

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);
    }
}
?>

clothohk at gmail dot com (15-Apr-2008 04:15)

Adding a space is not a solution to my Chinese UTF-8 characters. I guess it will not work for Japanese and Korean too.

I use this instead:
$filename = mb_substr($path, mb_strrpos($path, '/')+1);

adrian at foeder dot de (20-Dec-2007 08:33)

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:

<?php
//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.

mike at mike-griffiths dot co dot uk (10-Sep-2007 11:20)

If you are trying to get the file extension of a given file then you should see the function pathinfo(), exploding by '.' on basename() is also possible (as long as you use the last array entry).

<?PHP
// Make an array of the various attributes
$path_parts = pathinfo('/www/htdocs/index.html');

$extension = $path_parts['extension'];

echo
$extension; // 'html'

?>

Hope this helps someone.

stephane dot fidanza at gmail dot com (11-Apr-2007 12:33)

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)

phdwight at yahoo dot com (22-Mar-2007 02:41)

Pulled my hair out for this.

Just like most functions, this does not play well with Japanese characters.

When you call basename with some Japanese characters, it will return nothing (truncates it) .

thoughts at highermind dot org (30-Jan-2007 01:45)

Basename without query string:

<?php
$filename   
= array_shift(explode('?', basename($url_path)));
?>

jonmsawyer at gmail dot com (09-Jan-2007 08:23)

@antrik at users dot sf dot net
> 15-Nov-2004 10:40
> When using basename() on a path to a directory
> ('/bar/foo/'), the last path component ('foo') is returned,
> instead of the empty string one would expect. (Both PHP
> 4.1.2 and 4.3.8 on GNU/Linux.) No idea whether this is
> considered a bug or a feature -- I found it extremely
> annoying. Had to work around using: <?php
> $file=substr($path, -1)=='/'?'':basename($path)
>
?> Watch out!

There is a reason behind this -- and it has nothing to do with being a feature. PHP was heavily modeled off of the POSIX model. Many of the same functions you see in PHP are also in C, C++, and Java. These languages are modeled on POSIX as well.

The directory '/bar/foo/', when passed into the function basename(), will output 'foo' because *everything*, including directories, in the POSIX model, is a _file_. Most unix platforms, and all Windows platforms are (some Linux distributions are not) fully compliant to the POSIX model.

For example, the device file that contains information about your harddisk, in Linux, is probably stored in the _file_ /dev/hda.

Another example is that when you want to list information about your CPU or Memory using the Linux kernel, you might read the _file_ /proc/cpu/info.

Directories are no exception. Directories are no more different than your regular text file -- other than the fact that they describe a _file_-list of all files under it, and where the OS can access them. This means that even directories treat other directories as files.

The reason why we are made to think that directories are not files is because the kernel (the OS) simply treats these culprits differently. Your OS is lying to you! When you try to open up c:\windows in Notepad, you simply get a runaround because the Windows operating system knows it is a directory and knows how to treat it -- and knowing this it will not let you open it up for editing. For if you did that, you would probably lose the data in that directory. If you are familiar with C programming, you will know that if you lose information about a pointer to an object, the object gets lost in memory. The same would happen if you modified a directory in the wrong way. This is why the operating system protects its directories with the upmost care. (Some do anyway, hehe)

So when doing any kind of programming in PHP, C/++, Java, Ada, Perl, Python, Ruby, FORTRAN, and yes, even RPG IV (for all of you AS/400 folks out there working on the IFS), you must treat directories as files well.

This is why 'foo' is returned. For more information on POSIX, see http://en.wikipedia.org/wiki/POSIX

I hope this helps. Cheers.

thovan at gmx dot net (02-Jan-2007 03:24)

After reading all of the earlier comments, I made my own function file_basename():

<?php
function file_basename($file= null) {
    if(
$file=== null || strlen($file)<= 0) {
        return
null;
    }
   
   
$file= explode('?', $file);
   
$file= explode('/', $file[0]);
   
$basename= $file[count($file)-1];

    return
$basename;   
}

?>

(19-Sep-2006 07:28)

lazy lester is just confirming what icewind said.
And yes it is correct! unlike what the following comment after icewind says, as that example is the same with the line order reversed! as poniestail at gmail dot com says.

But poniestail at gmail dot com missed the point that if the url is coming from a log file it will not have its value in $_SERVER["QUERY_STRING"] or $_SERVER["SCRIPT_NAME"] but in a LOG FILE or a DATABASE

lazy lester (18-Feb-2006 12:19)

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];
?>

support at rebootconcepts dot com (17-Feb-2006 07:55)

works on windows and linux, faster/easier than amitabh's...

<?php
$basename
= preg_replace( '/^.+[\\\\\\/]/', '', $filename );

// Optional; change any non letter, hyphen, or period to an underscore.
$sterile_filename = preg_replace( "/[^\w\.-]+/", "_", $basename );
?>

poniestail at gmail dot com (05-Jan-2006 12:18)

examples from "icewind" and "basname" seem highly overdone... not to mention example from "basename" is exactly the same as one from "icewind"...

possibly a more logical approach?
<?
   //possible URL = http://domain.com/path/to/file.php?var=foo
   $filename = substr( $_SERVER["SCRIPT_NAME"], 1 ); //substr( ) used for optional removal of initial "/"
   $query = $_SERVER["QUERY_STRING"];
?>

to see the entire $_SERVER variable try this:
<?
   echo "<pre>
      ".print_r( $_SERVER, true )."
      </pre>
   ";
?>

(15-Nov-2005 12:57)

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.

icewind (02-Nov-2005 08:44)

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 (24-Oct-2005 08:47)

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!

crash at subsection dot org dot uk (22-Sep-2005 08:38)

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

b_r_i_a__n at locallinux dot com (23-Aug-2005 01:47)

I was looking for a way to get only the filename whether or not I had received the full path to it from the user.  I came up with a much simpler (and probably more robust) method by using the power of basename in reverse:

$infile = "/usr/bin/php";
$filename = stristr ($infile,basename ($infile));

This even works on those _wacky_ filenames like "/usr/lib/libnetsnmp.so.5.0.9" which are not factored when exploding the full path and taking out only the last segment after "."

pvollma at pcvsoftware dot net (14-Jul-2005 05:28)

Note that in my example below, I used the stripslashes function on the target string first because I was dealing with the POST array $_FILES. When creating this array, PHP will add slashes to any slashes it finds in the string, so these must be stripped out first before processing the file path. Then again, the only reason I can think of that basename() would fail is when dealing with Windows paths on a *nix server -- and the file upload via POST is the only situation I can think of that would require this. Obviously, if you are not dealing with these additional slashes, invoking stripslashes() first would remove the very separators you need extract the file name from the full path.

amitabh at NOSPAM dot saysnetsoft dot com (14-Jul-2005 09:55)

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);
        }
}
?>

pvollma at pcvsoftware dot net (13-Jul-2005 07:43)

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
$filen
= stripslashes($_FILES['userfile']['name']);
$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 (30-Jan-2005 02:18)

if you want the name of the parent directory
<?php
$_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.'<br>');
echo(
'$_parenDir  = '.$_parenDir.'<br>');
echo(
'$_parenDir2  = '.$_parenDir2.'<br>');
?>

KOmaSHOOTER at gmx dot de (30-Jan-2005 12:24)

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   
?>

antrik at users dot sf dot net (15-Nov-2004 06:40)

When using basename() on a path to a directory ('/bar/foo/'), the last path component ('foo') is returned, instead of the empty string one would expect. (Both PHP 4.1.2 and 4.3.8 on GNU/Linux.) No idea whether this is considered a bug or a feature -- I found it extremely annoying. Had to work around using: <?php $file=substr($path, -1)=='/'?'':basename($path) ?> Watch out!

osanim at cidlisuis dot org (17-Apr-2004 07:12)

If you want know the real directory of the include file, you have to writte:

<?php
dirname
(__FILE__)
?>

KOmaSHOOTER at gmx dot de (28-Nov-2003 10:33)

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])
?>

giovanni at giacobbi dot net (08-Nov-2003 03:52)

No comments here seems to take care about UNIX system files, which typically start with a dot, but they are not "extensions-only".
The following function should work with every file path. If not, please let me know at my email address.

<?php

function remove_ext($str) {
 
$noext = preg_replace('/(.+)\..*$/', '$1', $str);
  print
"input: $str\n";
  print
"output: $noext\n\n";
}

remove_ext("/home/joh.nny/test.php");
remove_ext("home/johnny/test.php");
remove_ext("weirdfile.");
remove_ext(".hiddenfile");
remove_ext("../johnny.conf");

daijoubu_NOSP at M_videotron dot ca (16-Oct-2003 06:22)

An faster alternative to:

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

would be:

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

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

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

Richard at Lyders dot Net (01-Apr-2003 09:53)

you can also make use of the basename() function's second parameter:

<?PHP
$fpath
= "/blah/file.name.has.lots.of.dots.ext";
$fext  = array_pop(explode('.', $fpath));
$fname = basename($fpath, '.'.$fext);

print
"fpath: $fpath\n<br>";
print
"fext: $fext\n<br>";
print
"fname: $fname\n<br>";
?>