Oti Na Nai
Oti Na Nai

Reputation: 1407

PHP Get path of file

Somewhere in my pc there is a txt file, test.txt let's call it, but its location may vary from pc to pc. Is there a way, to get that path so that it can be read? I can use of course

$file = file_get_contents(path);

But that comes when you already know the current path. How can I retrieve the path in this case? Ty

Upvotes: 1

Views: 72

Answers (1)

chiliNUT
chiliNUT

Reputation: 19573

If you are on a linux/unix box, you can use locate and parse the result. windows probably has a similar solution:

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

Upvotes: 1

Related Questions