Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file_exists() says existing file does not exist

Tags:

php

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

like image 879
electrikmilk Avatar asked Dec 10 '25 21:12

electrikmilk


2 Answers

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;
}
like image 72
Spudley Avatar answered Dec 13 '25 09:12

Spudley


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.

like image 20
Martin Lantzsch Avatar answered Dec 13 '25 11:12

Martin Lantzsch