Webeng Webeng - 1 year ago 148
PHP Question

Check if file exists on another website

I've been trying to develope code that would check if a pdf file exists on another website. For testing purposes, I found a random pdf file online:


I tried the following code and neither of the two methods worked:

Method 1:

$path1 = 'http://www.tutorialspoint.com/php/php_tutorial.pdf';
if (file_exists($path1))
echo "found!";
echo "not found";

//RESULT: not found

Method 2:

function UR_exists($url){
return stripos($headers[0],"200 OK")?true:false;

echo "This page exists";
echo "This page does not exist";

//RESULT: This page does not exist

The page executes fine in both situations, but the result is always that the file doesn't exist, when I know it exists lol. What am I doing wrong?

Answer Source

file_exists uses physical paths, the parameter you need to provide should be the address on that server where the file can be found, and not an url! in the other hand the header method should be working fine! but testing against 404 header response is worth trying and you can do it like so:

$url = "http://www.tutorialspoint.com/php/php_tutorial.pdf";
$header_response = get_headers($url);
if (header_response) {
    if ( strpos( $header_response[0], "404" ) !== false ){
        echo "PDF DOES NOT EXIST";
      // PDF EXISTS!!
        echo "PDF EXISTS";
}else {
    echo "PDF DOES NOT EXIST";

please keep in mind that allow_url_fopen = 1 which allows you to use external URLs should be enabled