Reputation: 31
In php,I have to find whether a directory exist. IF it exists not a problem (I will display the hyperlink for that using the dirname)
Here is the sample in which I need help.
dir_name is the directory name
$url = system(~'ls -d /home/myapps/rel/".$dir_name"');
echo $url;(this does not work)
if(preg_match("/No such/",$url)) {
echo'Ther is no match'
}
else{
}
In my code the if block is never executed.(it should execute if the directory does not exist) ;(
Upvotes: 3
Views: 1540
Reputation: 454912
As others have told, is_dir
is the right way to go.
I'll point out why your existing program does not work. This will be useful in cases when you want to run an external command and then parse its output.
~
in your call
to system
.Variable interpolation does not happen in single quotes. So you need do something like:
system('ls -d /home/myapps/rel/'.$dir_name);
or
system("ls -d /home/myapps/rel/$dir_name");
Even with the above changes it does
not work because if the dir does not
exist, ls issues the "....not
found"
error on stderr
and not on
stdout
and system just returns the
last line of the stdout
. To fix
this we need to redirect stderr
of
the command to stdout
as:
system("ls -d /home/myapps/rel/$dir_name 2>&1");
You also need to remember that
system
returns only the last
line of the output. In the current
case if works, but in some other
cases if the external command being
run spits many lines of error/output
system
will not work and you'll have
to use exec
which allows you to
collect entire output lines in an
array. Something like:
exec("ls -d /home/myapps/rel/$dir_name 2>&1",$output_arr);
then you can search for your err string in the array $output_arr
So now you have the error message(if the dir does not exist) in $url
and then check for the presence of string "No such"
.
Some more problems with the approach:
/foo/bar not found
and this
can cause your solution to break.$dir_name
contains the string No such
( weird
but possible) your solution will
break.Upvotes: 4
Reputation: 1739
http://php.net/manual/en/function.file-exists.php
bool file_exists ( string $filename )
Returns true if file or directory exists. If you then need to find it out if its directory or file use is_dir()
Upvotes: 2
Reputation: 11286
Why don't you use is_dir()
?
http://php.net/manual/en/function.is-dir.php
Upvotes: 8