2

Possible Duplicate:
Easy way to test a URL for 404 in PHP?

I am using curl to download a sequence of pdfs from the backend in PHP. I do not know when the sequence ends like 1.pdf, 2.pdf......etc.

Below is the code I am using to download pdf:

$url  = 'http://<ip>.pdf';
    $path = "C:\\test.pdf";
 
    $fp = fopen($path, 'w');
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
 
    $data = curl_exec($ch);
    
    fclose($fp);

But how do I determine that that pdf do not exists in the backend? Does curl returns any response when file not found?

Nimantha
  • 5,793
  • 5
  • 23
  • 56
aandroidtest
  • 1,455
  • 7
  • 39
  • 67

2 Answers2

2
$ch=curl_init("www.example.org/example.pdf");
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result=curl_exec($ch);
curl_close($ch);

with curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); it will return the result on success, FALSE on failure.

with curl_setopt($ch,CURLOPT_RETURNTRANSFER,false); it will return TRUE on success or FALSE on failure.

Moreover, for file not found:

$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code == 404)
{
  /*file not found*/
}
Patt Mehta
  • 4,034
  • 1
  • 21
  • 45
1

Just test the statut code of the http response after $data = curl_exec($ch);

$http_status = curl_getinfo($url, CURLINFO_HTTP_CODE);
if($http_status == '404') {

   //not found, -> file doesnt exist in your backend
}

More info here

Pierrickouw
  • 4,584
  • 1
  • 28
  • 29