我一直在尝试开发代码来检查另一个网站上是否存在pdf文件。出于测试目的,我在网上找到了一个随机的pdf文件:
http://www.tutorialspoint.com/php/php_tutorial.pdf
我尝试了以下代码,但这两种方法都不起作用:
方法一:
$path1 = 'http://www.tutorialspoint.com/php/php_tutorial.pdf';
if (file_exists($path1))
{
echo "found!";
}
else
{
echo "not found";
}
//RESULT: not found
方法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
页面在这两种情况下都执行得很好,但结果总是该文件不存在,当我知道它存在时,哈哈。我做错了什么?
file_exists
使用物理路径,您需要提供的参数应该是该服务器上可以找到文件的地址,而不是URL!另一方面,标题方法应该工作正常!但是针对 404 标头响应进行测试值得尝试,您可以这样做:
$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";
}
请记住,应启用允许您使用外部 URL 的allow_url_fopen = 1