Reputation: 1043
I'm trying to check if an XML file exists, depending on a username parameter
<?php
$username = $_GET["username"];
$filename = "/documents/$username/data.xml";
if (file_exists($filename)) {
// output documents
} else {
echo "No documents exist in your account.";
}
?>
It continues to return that the file doesn't exist.
Full path: http://example.com/documents/{username}/data.xml
Why does it continue to return false when I know the file exists?
EDIT: I made this post years ago, this is definitely not the best way to keep user data, but the answers to this post serve as good explanations of file_exists().
Upvotes: 2
Views: 4547
Reputation: 9527
file_exist
check local files. If you want to check files via URL use
fopen()
- that returns NULL is file has not been opened
or cURL
(visit: How can one check to see if a remote file exists using PHP?)
$ch = curl_init("http://example.com/userdata/johndoe1/docs.xml");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode > 400 -> not found, $retcode = 200, found.
curl_close($ch);
Upvotes: 3
Reputation: 1901
file_exists checks if a file exists in your local or in a mounted file system of your computer. It cannot check remote files via http.
To test this, you can try getting the file and validate the sent header:
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = get_headers($file);
$exists = ($file_headers[0] != 'HTTP/1.1 404 Not Found');
$exists is true when the file exists and false if the file doesnt exist.
Upvotes: 3
Reputation: 168655
The file_exists()
function is designed for checking a local file on the same server as the PHP code.
In common with other file handling functions, it can also read URLs, but this feature can be considered a security risk, and many servers disable it, and restrict you to only reading files from the local server.
You should check whether your server allows you to do this or not. If not, you will have to use a different method to read the remote URL, for example, using CURL.
Please also see the comments in the file_exists()
manual page; one entry explictly gives an answer for how to read a remote file. Here's the code quoted from the manual comment:
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
Upvotes: 3