Skip to content

Instantly share code, notes, and snippets.

@vyspiansky
Last active March 1, 2021 16:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vyspiansky/10959566 to your computer and use it in GitHub Desktop.
Save vyspiansky/10959566 to your computer and use it in GitHub Desktop.
PHP: file_exists for remote URL
<?php
// More details here:
// https://vyspiansky.github.io/2017/11/09/remote-file-exists-using-get-headers/
$file_headers = @get_headers($url);
if ($file_headers[0] == 'HTTP/1.0 404 Not Found'){ // or "HTTP/1.1 404 Not Found" etc.
$file_exists = false;
} else {
$file_exists = true;
}
@shaikhAli
Copy link

shaikhAli commented Aug 29, 2016

not working

$url="http://www.gallinews.com/admin/cover_image/mashuhoor-hona.jpg";
$file_headers = @get_headers($url);
if ($file_headers[0] == 'HTTP/1.0 404 Not Found'){
    $file_exists = false;
} else {
    $file_exists = true;
}
echo $file_exists;

@yumyo
Copy link

yumyo commented Jan 3, 2017

The snippet works as shown here http://sandbox.onlinephpfunctions.com/

Have you checked your server allow_url_fopen php setting?

@alaminshakeel
Copy link

i have no access on my server php setting i am service subscriber.. how do i check my server?

@vyspiansky
Copy link
Author

vyspiansky commented Nov 9, 2017

To check if allow_url_fopen is enabled or not you can use ini_get():

if (ini_get('allow_url_fopen')) {
    echo "allow_url_fopen is enabled";
}

Or just print the get_headers:

$url = 'some url here...';
$file_headers = @get_headers($url);
print_r($file_headers);

and you should see something like:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Content-Type: image/png
    [2] => Content-Length: 127999
    [3] => Connection: close
    [4] => Date: Thu, 09 Nov 2017 12:16:51 GMT
    [5] => Last-Modified: Wed, 08 Nov 2017 09:12:17 GMT
    ...
)

Be careful, the message may have the different version of the protocol: "HTTP/1.0 404 Not Found" or "HTTP/1.1 404 Not Found" etc.

@TRClint
Copy link

TRClint commented Aug 14, 2020

I use the following so that I do not have to worry about HTTP/1.0 or 1.1, etc.

if(strpos($file_headers[0], '404') !== false)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment