I want to store a path (pointing to a directory) in a text file and open the path when required in PHP. Here’s what I have done, which is quite simple but doesn’t really work.
$dir = file_get_contents('./dir_file');
$dir_content = get_fname($dir);
function get_fname($dir) {
$dirhandle = opendir($dir);
if (!dirhandle) { exit; }
.........
}
The value of $dir is what it is in the text file. The code doesn’t work. The function exits in the if statement.
I tried to replace the first line with
$dir = '/home/user/work'; //which is the path stored in the text file.
It works. So I suspect it’s the problem of opendir. I can’t figure out what causes this problem.
Any help will be appreciated. Many thanks.
Check if the file you’re reading from has any line breaks, spaces, etc… after the actual path part. If you pass those in to opendir, it’s going to look for a directory which has those literal characters in it, and most likely fail.
Adding a trim() call may help:
which will remove any such whitespace characters.