2015-04-25 6 views
1

Где-то на моем компьютере есть txt-файл, test.txt давайте назовем его, но его местоположение может отличаться от pc to pc. Есть ли способ, чтобы получить этот путь, чтобы его можно было прочитать? Я могу использовать, конечно,PHP Получить путь к файлу

$file = file_get_contents(path); 

Но это происходит, когда вы уже знаете текущий путь. Как я могу получить путь в этом случае? Ty

+1

'glob (path)' ....... – adeneo

ответ

1

Если вы находитесь в поле linux/unix, вы можете использовать locate и разобрать результат. окна, вероятно, имеют аналогичное решение:

<?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]); 
    } 
}