Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: pathinfo - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

pclose" width="11" height="7"/> <parse_ini_file
Last updated: Sun, 25 Nov 2007

view this page in

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo — ファイルパスに関する情報を返す

説明

mixed pathinfo ( string $path [, int $options ] )

pathinfo() は、path に関する情報を有する連想配列を返します。

パラメータ

path

調べたいパス。

options

どの要素を返すのかをオプションのパラメータ options で指定します。これは PATHINFO_DIRNAMEPATHINFO_BASENAMEPATHINFO_EXTENSION および PATHINFO_FILENAME の組み合わせとなります。 デフォルトではすべての要素を返します。

返り値

以下の要素を含む連装配列を返します。 dirname (ディレクトリ名)、basename (ファイル名) そして、もし存在すれば extension (拡張子)。

options を使用すると、 すべての要素を選択しない限りこの関数の返り値は文字列となります。

変更履歴

バージョン 説明
5.2.0 定数 PATHINFO_FILENAME が追加されました。

Example#1 pathinfo() の例

<?php
$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"// PHP 5.2.0 以降
?>

上の例の出力は以下となります。

/www/htdocs
index.html
html
index

注意

注意: カレントのパスに関する情報を取得するには、 定義済みの変数 のセクションをご覧ください。



pclose" width="11" height="7"/> <parse_ini_file
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
pathinfo
christian dot reinecke at web dot de
25-Feb-2008 12:46
if you call pathinfo with a filename in url-style (example.php?with=parameter), make sure you remove the given parameters before, otherwise they will be returned as part of the extension.

extension => php?with=parameter
tom at foo-bar dot co dot uk
30-Jan-2008 11:48
Note that this function seems to just perform string operations, and will work even on a non-existent path, e.g.

<?php
print_r
(pathinfo('/no/where/file.txt'));
?>

which will output:
Array
(
    [dirname] => /no/where
    [basename] => file.txt
    [extension] => txt
    [filename] => file
)
OakBehringer
28-Jan-2008 10:47
Building on David Blinco's function, the following will:

1. Return the correct protocol for secure requests (https)
2. Throw an exception for invalid files
3. Ensure the returned url separates directories with forward slashes (David's will not on Windows systems).

function mapPath ($filepath) {
    $realpath = realpath($filepath);
    $dir;
   
    // Verify that the path passed is real and harvest the bottom directory
    if (is_file($realpath)) {
        $dir = dirname($realpath);
    }
    elseif (is_dir($realpath)) {
        $dir = $realpath;
    }
    else {
        throw new Exception('File does not exist: ' . $realpath);
    }

    // Make sure the path is not lower than the server root
    if (strlen($dir) < strlen($_SERVER['DOCUMENT_ROOT']))
        throw new Exception("Cannot create http path below server http root.");
       
    $path = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . substr($realpath, strlen($_SERVER['DOCUMENT_ROOT']));
   
    if (DIRECTORY_SEPARATOR == '\\')
        $path = str_replace('\\', '/', $path);

    return $path;
}
davidblinco at gmail dot com
27-Jan-2008 12:27
This function is not perfect, but you can use it to convert a relative path to a URL.
Please email me if you can make any improvements.

<?php
function mapURL($relPath) {
   
$filePathName = realpath($relPath);
   
$filePath = realpath(dirname($relPath));
   
$basePath = realpath($_SERVER['DOCUMENT_ROOT']);
   
   
// can not create URL for directory lower than DOCUMENT_ROOT
   
if (strlen($basePath) > strlen($filePath)) {
        return
'';
    }
   
    return
'http://' . $_SERVER['HTTP_HOST'] . substr($filePathName, strlen($basePath));
}
?>
henrik at not-an-address dot com
22-Dec-2007 03:23
If you have filename with utf-8 characters, pathinfo will strip them away:

print_r(pathinfo("/mnt/files/飛兒樂團光茫.mp3"));

 .. will display:

Array
(
    [dirname] => /mnt/files
    [basename] => .mp3
    [extension] => mp3
    [filename] =>
)
mrnemesis at ntlworld dot com
20-Dec-2007 12:22
Note that in PHP 4 (if you're stuck using it), pathinfo only provides dirname, basename, and extension, but not filename. This function will not split a file's stem and extension for you.
anders.jenbo()pc.dk
12-Sep-2007 06:34
Heres a funciton to get the same results from php 4+ but you will have to call pathinfo_filename() instead of pathinfo().

<?php
if(version_compare(phpversion(), "5.2.0", "<")) {
    function
pathinfo_filename($path) {
       
$temp = pathinfo($path);
        if(
$temp['extension'])
           
$temp['filename'] = substr($temp['basename'],0 ,strlen($temp['basename'])-strlen($temp['extension'])-1);
        return
$temp;
    }
} else {
    function
pathinfo_filename($path) {
        return
pathinfo($path);
    }
}
?>
avi-team at inbox dot lv
16-Jul-2007 12:14
You shouldn't assign values as it is described in previous post
// wrong:
list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) );

if $file has no extension, you get wrong variable values: $extension would be assigned with 'filename' array element of pathinfo() result, but $filename - would be empty.
phpnet at whoisgregg dot com
31-May-2007 03:01
If you want to easily assign the values returned by pathinfo to separate variable names, list isn't enough. You can use array_values() first to convert the associative array into the indexed array that list() expects:

// throws notices, variables aren't set
list( $dirname, $basename, $extension, $filename ) = pathinfo($file);

// works
list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) );
cochise_chiracahua at hotmail.com
26-Nov-2005 04:55
Sometimes, it's interessant to get the basename without extension.
So, I appended a new entry 'basenameWE' (Basename Without Extension) to the returned array.

<?php

// pathinfo improved
function pathinfo_im($path) {
   
   
$tab = pathinfo($path);
   
   
$tab["basenameWE"] = substr($tab["basename"],0
   
,strlen($tab["basename"]) - (strlen($tab["extension"]) + 1) );
   
    return
$tab;
}

$my_path = "/var/www/html/example.html";

echo
"<pre>\n";
print_r( pathinfo_im($my_path) );
echo
"</pre>\n";

?>

Out :

Array
(
    [dirname] => /var/www/html
    [basename] => example.html
    [extension] => html
    [basenameWE] => example
)
sgermain at icexnetworks dot com
09-Jul-2005 03:24
It is true that if you put a directory into pathinfo, usually the extension is empty. But, if the directory name is /www/example.com/ for example, you will have the following output:

Array
(
    [dirname] => /www
    [basename] => example.com
    [extension] => com
)

So, it is the same as a file.
n0dalus
08-Feb-2005 06:47
If a file has more than one 'file extension' (seperated by periods), the last one will be returned.
For example:
<?php
$pathinfo
= pathinfo('/dir/test.tar.gz');
echo
'Extension: '.$pathinfo['extension'];
?>
will produce:
Extension: gz

and not tar.gz
03-Dec-2004 09:39
If you want only the file extension, use this:
<?php
$extension
= substr(strrchr($filename, "."), 1);
?>
This is many times faster than using pathinfo() and getting the value from array.
rob at webdimension dot co dot uk
04-Oct-2004 10:48
Further to my previous post.

This affects servers that run PHP as a cgi module

If you have your own server:
You can use the AcceptPathInfo directive to force the core handler to accept requests with PATH_INFO and thereby restore the ability to use PATH_INFO in server-side includes.

Further information:
http://httpd.apache.org/docs-2.0/mod/core.html#acceptpathinfo
junk at plaino dot com
19-Aug-2004 10:41
Convert a URL to the local file path and vice versa, convert a local file path to a URL.

// this sets the sytem / or \ :
strstr( PHP_OS, "WIN") ? $slash = "\\" : $slash = "/";

// This is the location of the php file that contains this
// function. Usually this request is made to files/folders
// down the directory structure, so the php file that
// contains these functions is a good "where am i"
// reference point:
$WIMPY_BASE['path']['physical'] = getcwd();
$WIMPY_BASE['path']['www'] = "http://".$_SERVER['HTTP_HOST'];

function url2filepath($theURL){
    global $WIMPY_BASE, $slash;
    $AtheFile = explode ("/", $theURL);
    $theFileName = array_pop($AtheFile);
    $AwimpyPathWWW = explode ("/", $WIMPY_BASE['path']['www']);
    $AtheFilePath = array_values (array_diff ($AtheFile, $AwimpyPathWWW));
    if($AtheFilePath){
        $theFilePath = $slash.implode($slash, $AtheFilePath).$slash.$theFileName;
    } else {
        $theFilePath = implode($slash, $AtheFilePath).$slash.$theFileName;
    }
    return ($WIMPY_BASE['path']['physical'].$theFilePath);
}

function filepath2url ($theFilepath){
    global $WIMPY_BASE, $slash;
    $AtheFile = explode ($slash, $theFilepath);
    $theFileName = array_pop($AtheFile);
    $AwimpyPathFILE = explode ($slash, $WIMPY_BASE['path']['physical']);
    $AtheFilePath = array_values (array_diff ($AtheFile, $AwimpyPathFILE));
    $thFileURL = implode("/", $AtheFilePath)."/".$theFileName;
    return ($WIMPY_BASE['path']['www']."$thFileURL");
}
albertof at deltasoft dot com dot ar
29-May-2002 05:10
This code is to work in index.php/var/var

if(isset($PATH_INFO)) {
      $viewcode = explode('/', $PATH_INFO);
        $num = count($viewcode);
        if($num % 2 == 0) {
            $viewcode[] = '';
            $num++;
        }
        for($i = 1; $i < $num; $i += 2) {

            $$viewcode[$i] = $viewcode[$i+1];

          }
    }
m-symons at home dot com
25-Aug-2001 11:01
And, of course, to account for the problem noted in the first post whereby calling a directory, not a file, messes with the output of pathinfo(), you can include the following test:

if($pathinfo[extension] == "") {

$deep++;

}

Ooops...sorry for missing that.
m-symons at home dot com
25-Aug-2001 10:54
Here's a neat wee function to grab the relative path to root (especially useful if you're using mock-directories to pass variables into scripts with mod_rewrite).  The function simply iterates through every occurence of "/" within the REQUEST_URI environment variable, appending "../" to the output for every instance:

<?php

function path_to_root($path) {

   
$pathinfo = pathinfo($path);
   
   
$deep = substr_count($pathinfo[dirname], "/");
   
   
$path_to_root = "./";
   
    for(
$i = 1; $i <= $deep; $i++) {
   
       
$path_to_root .= "../";
       
    }
   
    return
$path_to_root;
}

path_to_root($REQUEST_URI);

?>
mikep at oeone dot com
23-Aug-2001 02:27
If you run this on a directory, basename is the last directory in the path, dirname is the path before the final directory and extension is empty.

pclose" width="11" height="7"/> <parse_ini_file
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites