1

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

1
  • 1
    glob(path) ....... Commented Apr 25, 2015 at 1:27

1 Answer 1

1

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.