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