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

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

php - Check if files with absolute and relative path exists

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

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

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...