PHP获取文件路径

时间:2015-04-25 01:25:03

标签: php

在我的电脑的某个地方有一个txt文件,test.txt让我们调用它,但它的位置可能因电脑而异。有没有办法,让这条路可以读取?我当然可以使用

$file = file_get_contents(path);

但是当你已经知道当前的路径时就会发生这种情况。在这种情况下如何检索路径? TY

1 个答案:

答案 0 :(得分:1)

如果您使用的是linux / unix框,则可以使用locate并解析结果。 Windows可能有类似的解决方案:

<?php

$search = "test.txt";

$result = shell_exec("locate $search");
//array of all files with test.txt in the name

$matchingFiles = explode(PHP_EOL, $result);

//that gets files that may be named something else with test in the name
//like phptest.txt so get rid of the junk

$files = array(); //array where possible candidates will get stored

if (!empty($matchingFiles)) {
    //we found at least 1
    foreach ($matchingFiles as $f) {
        //if the file is named test.txt, and not something like phptest.txt
        if (basename($f) === $search) {
            $files[] = $f;
        }
    }
}

if (empty($files)) {
    //we didn't find anything
    echo $search . ' was not found.';
} else {
    if (count($files) > 1) {
        //we found too many. which one do you want?
        echo "more than one match was found." . PHP_EOL;
        echo print_r($files, true);
    } else {
//then we probably found it
        $file = file_get_contents($files[0]);
    }
}