Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if files with absolute and relative path exists

Tags:

path

php

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.

like image 820
uji Avatar asked Nov 13 '09 16:11

uji


People also ask

How do you tell if a path is relative or absolute?

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).

What is absolute path and relative path in CMD?

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").

How do you know if a path is absolute or relative in Python?

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.


2 Answers

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);
}
like image 109
Stepan Mazurov Avatar answered Sep 19 '22 11:09

Stepan Mazurov


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
}
like image 37
Gumbo Avatar answered Sep 20 '22 11:09

Gumbo