简体   繁体   中英

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:

http://www.tutorialspoint.com/php/php_tutorial.pdf

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!";
}
else
{
  echo "not found";
}

//RESULT: not found

Method 2:

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

if(UR_exists('http://www.tutorialspoint.com/php/php_tutorial.pdf'))
   echo "This page exists";
else
   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?

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 ){
      // PDF DOES NOT EXIST
        echo "PDF DOES NOT EXIST";
    }else{
      // 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM