PHP Curl get server response [duplicate]

<strong>Possible Duplicate:</strong> 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?

Thanks In Advance

Answer1:

$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*/ }

Answer2:

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

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:PHP Curl get server response [duplicate]