Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_exists() returns false even if file exist (remote URL)

Tags:

php

My file_exists() returns false even if provided image to check https://www.google.pl/logos/2012/haring-12-hp.png exist. Why?

Below I am presenting full failing PHP code ready to fire on localhost:

$filename = 'https://www.google.pl/logos/2012/haring-12-hp.png';
echo "<img src=" . $filename . " />";
if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
like image 865
Szymon Toda Avatar asked May 04 '12 06:05

Szymon Toda


People also ask

How to check url file exist or not in php?

The file_exists() function in PHP, is used to check if a file or directory exists on the server. But the file_exists() function will not usable if you want to check the file existence on the remote server. The fopen() function is the easiest solution to check if a file URL exists on a remote server using PHP.

Which of the following returns true if the file at the specified path exists or false otherwise?

exists(): Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise. Files.

How do you check if a file already exists in PHP?

The file_exists() function checks whether a file or directory exists.

How do you create a file if it doesn't exist in PHP?

PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).


2 Answers

$filename= 'https://www.google.pl/logos/2012/haring-12-hp.png';
$file_headers = @get_headers($filename);

if($file_headers[0] == 'HTTP/1.0 404 Not Found'){
      echo "The file $filename does not exist";
} else if ($file_headers[0] == 'HTTP/1.0 302 Found' && $file_headers[7] == 'HTTP/1.0 404 Not Found'){
    echo "The file $filename does not exist, and I got redirected to a custom 404 page..";
} else {
    echo "The file $filename exists";
}
like image 157
Gilly Avatar answered Sep 24 '22 01:09

Gilly


A better if statement that not looks at http version

$file_headers = @get_headers($remote_filename);    
if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
//throw my exception or do something
}
like image 33
Maurizio Brioschi Avatar answered Sep 25 '22 01:09

Maurizio Brioschi