在写框架和项目时候我们经常要获取绝对路径,php有内置函数realpath(),  也可以写个函数来实现这个功能

function getAbsolutePath($path) {
    $path  = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
    $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
    $absolutes = array();
    foreach ($parts as $part) {
        if ('.' == $part){
            continue;
        }
        if ('..' == $part) {
            array_pop($absolutes);
        } else {
            $absolutes[] = $part;
        }
    }
    return DIRECTORY_SEPARATOR.ltrim(implode(DIRECTORY_SEPARATOR, $absolutes),DIRECTORY_SEPARATOR);
}

 

 laravel框架入口文件就有段引入文件目录

$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);


测试下
echo getAbsolutePath(__DIR__.'/../').'<br>';
echo realpath(__DIR__.'/../');

【php】php目录路径函数系列

 注意一点  对于php内置函数realpath()  会对路径判断是否存在

比如

var_dump(realpath(__DIR__.'/images/addBtn1.png')) ;  这个返回false
var_dump(realpath(__DIR__.'/images/addBtn.png')) ;   这个文件存在返回该路径

 

相关文章:

  • 2022-12-23
  • 2021-07-19
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-23
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-12-18
  • 2021-08-08
相关资源
相似解决方案