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.
An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).
In the example above, the absolute path contains the full path to the cgi-bin directory on that computer. The relative path begins with a dot (period), representing the current directory (also called the "working directory").
isabs() method in Python is used to check whether the specified path is an absolute path or not. On Unix platforms, an absolute path begins with a forward slash ('/') and on Windows it begins with a backward slash ('\') after removing any potential drive letter.
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);
}
You can use realpath
to check if a file exists to the given path and retrieve the expanded path to that file:
$absPath = realpath($path);
if ($absPath === false) {
// invalid path
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With