PHP Curl获取服务器响应[重复]
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?
Thanks In Advance
可能重复: strong>
在PHP中测试404的URL的简便方法? blockquote>我正在使用curl从PHP的后端下载一系列pdf。 我不知道序列何时结束如1.pdf,2.pdf ......等。 p>
以下是我用来下载pdf的代码: p>
$ url ='http://&lt; ip&gt; .pdf'; $ path =“C:\\ test.pdf”; $ fp = fopen( $ path,'w'); $ ch = curl_init($ url); curl_setopt($ ch,CURLOPT_FILE,$ fp); $ data = curl_exec($ ch); \ n fclose($ fp); code> pre>
但是如何确定后端中不存在该pdf? 当找不到文件时,curl会返回任何响应吗? p>
在此先感谢 p> div>
$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*/
}
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