[PHP] 取得檔名和路徑:basename, dirname

URL Link //n.sfs.tw/10589

2017-01-10 09:04:22 By 張○○

由絕對路徑取的路徑及檔名的方法

法一
$path = "/home/httpd/html/index.php";
$file = basename($path);         // index.php
$file = basename($path, ".php"); //  index
$dir = dirname($path);         // /home/httpd/html 注意沒有尾端的 '/'

法二
$path = "/home/httpd/html/index.php";
$fs= pathinfo($path);
print_r($fs);
Array
(
    [dirname] => /home/httpd/html
    [basename] => index.php
    [extension] => php
    [filename] => index
)

法三
$info = new SplFileInfo('/home/httpd/html/index.php');
$fn= $info->getFilename();  //index.php
$dir= $info->getPath(); ///home/httpd/html
$path= $info->getPathname(); //home/httpd/html/index.php

利用類別的方法可以得到更多檔案的資訊,雖然看似麻煩,其實更方便[2]

參考資料

[1] http://stackoverflow.com/questions/1418193/how-to-get-file-name-from-full-path-with-php

[2] http://php.net/manual/en/class.splfileinfo.php