PHP获取文件的路径
在我的电脑中的某个地方有一个txt文件,我们称之为test.txt,但它的位置可能因电脑而异。有没有办法获取该路径以便读取?我当然可以用PHP获取文件的路径,php,Php,在我的电脑中的某个地方有一个txt文件,我们称之为test.txt,但它的位置可能因电脑而异。有没有办法获取该路径以便读取?我当然可以用 $file = file_get_contents(path); 但是,当你已经知道当前的路径时,就会出现这种情况。在这种情况下,如何检索路径?Ty如果您在linux/unix设备上,您可以使用定位并解析结果。windows可能有类似的解决方案: <?php $search = "test.txt"; $result = shell_exec("l
$file = file_get_contents(path);
但是,当你已经知道当前的路径时,就会出现这种情况。在这种情况下,如何检索路径?Ty如果您在linux/unix设备上,您可以使用
定位
并解析结果。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]);
}
}
全局(路径)
。。。。。。。