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'
开发者_如何学Python }
else{
}
In my code the if block is never executed.(it should execute if the directory does not exist) ;(
Why don't you use is_dir()
?
http://php.net/manual/en/function.is-dir.php
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.
- You have a unwanted
~
in your call tosystem
. Variable interpolation does not happen in single quotes. So you need do something like:
system('ls -d /home/myapps/rel/'.$dir_name);
orsystem("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 onstderr
and not onstdout
and system just returns the last line of thestdout
. To fix this we need to redirectstderr
of the command tostdout
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/outputsystem
will not work and you'll have to useexec
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:
- Some implementation of bash throw a
different err message when you list
for a non existing file. One I've
seen is
/foo/bar not found
and this can cause your solution to break. - Also if the value of
$dir_name
contains the stringNo such
( weird but possible) your solution will break.
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()
精彩评论