Reputation: 3517
This is madness, hoping someone can explain.
$dir = getcwd();
$a = "/var/www/vhosts/mysite/httpdocs/sub1";
$b = "/var/www/vhosts/mysite/httpdocs/sub2";
if( ($dir == $a) || ($dir == $b) ){
$dirlist = glob("../images2/spinner/*.jpg");
}else{
$dirlist = glob("images2/spinner/*.jpg");
}
works fine but
$dir = getcwd();
if( ($dir == "/var/www/vhosts/mysite/httpdocs/sub1") || ($dir == "/var/www/vhosts/mysite/httpdocs/sub2") ){
$dirlist = glob("../images2/spinner/*.jpg");
}else{
$dirlist = glob("images2/spinner/*.jpg");
}
doesn't. (By doesn't work I mean it returns false, I also tried === )
Anyone?
Upvotes: 1
Views: 245
Reputation: 54771
Looks like you have run into the if true then this else everything else bug
. You made the mistake of assuming that $dir
can only be $a
or $b
which as Luc M stated is not always the case.
We were just talking about this on programmer exchange yesterday.
https://softwareengineering.stackexchange.com/questions/206816/clarification-of-avoid-if-else-advice
Here is an alternative way of handling the logic.
$base = dirname(__FILE__);
$path = '/images2/spinner';
if(file_exists($base.$path))
{
$path = $base.$path;
}
else if(file_exists($base.'/../'.$path))
{
$path = $base.'/../'.$path;
}
else
{
throw new Exception('Images not found.');
}
$dirlist = glob($path.'/*.jpg');
I wouldn't hard code a host path into your logic. That will lend itself to more bugs. Try to use relative paths to the current source file when possible, and if you can't. Place your hard coded paths in a config.php
file as constants and include that file.That will store those values in one place.
Upvotes: 4
Reputation: 17314
Verify the value returned by getcwd()
From http://www.php.net/
Returns the current working directory on success, or FALSE on failure.
On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.
http://www.php.net/manual/en/function.getcwd.php
Upvotes: 3