Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to check whether files (with either an absolute or relative path) exists? Im using PHP. I found a couple of method but either they only accept absolute or relative but not both. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
621 views
Welcome To Ask or Share your Answers For Others

1 Answer

file_exists($file); does the trick for both relative and absolute paths.

What's more useful, however, is having absolute paths without hardcoding it. The best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether UNIX or Windows format. Then we can use realpath() which conveniently returns false if file does not exist. All you have to do then is specify a relative path from that file's directory and put it all together:

$path = dirname(__FILE__) . '/include.php';
if (realpath($path)) {
    include($path);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...