I’m having trouble using a variable for the directory name in this PHP if statement:
if (($handle = opendir("news"))) {
// Read all file from the actual directory
while ($file = readdir($handle)) {
if (!is_dir($file)) {
$fileList[] = $file;
}
}
}
When I use a variable ($newsDir) instead of a string literal for the directory name ("news"), the script stops working.
$newsDir = $_SERVER[DOCUMENT_ROOT] . "edit/news";
var_dump(file_exists($newsDir));
// bool(true)
var_dump(is_dir($newsDir));
// bool(true)
var_dump($newsDir);
// string(36) "/f5/jb-cms-testing/public//edit/news"
if (($handle = opendir($newsDir))) {
// Read all file from the actual directory
while ($file = readdir($handle)) {
if (!is_dir($file)) {
$fileList[] = $file;
}
}
}
It doesn’t throw any errors, the function just doesn’t properly run. At first, I thought it was because my $newsDir variable is $_SERVER[DOCUMENT_ROOT] . "edit/news", but even if I set $newsDir to just "news", it doesn’t work. So it’s something to do with the fact that I’m using a variable, as far as I can tell.
Any ideas why? Also, this is the only place, and the only file that $handle occurs, so I’m not sure why it works at all. It was a while ago that I built this, and I was using a tutorial, so I’m not sure exactly how it works. It’s basically just a way to sort files in the news directory.
Wow. I figured it out. It’s just that you apparently can’t use variables out side of a function. I was including the vars.php file outside of the function, which was causing the error. I have no idea why you wouldn’t be able to do this, maybe someone can enlighten me?
Thanks for all the input.