如何测试php中是否存在远程图像文件?
这会吐出一大堆“否”,但图像在那里,路径正确,因为它们是通过如何测试php中是否存在远程图像文件?,php,Php,这会吐出一大堆“否”,但图像在那里,路径正确,因为它们是通过显示的; } 文件\u exists查找本地路径,而不是“http://”URL 使用: 文件\u存在使用本地路径,而不是URL 解决办法是: $file = 'http://www.domain.com/somefile.jpg'; $file_headers = @get_headers($file); if($file_headers[0] == 'HTTP/1.1 404 Not Found') { $exists =
显示的;
}
文件\u exists查找本地路径,而不是“http://”URL
使用:
文件\u存在
使用本地路径,而不是URL
解决办法是:
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
更多信息请参见此
另外,查找响应头(使用函数)将是更好的选择。只需检查响应是否为404:
$url=getimagesize(your_url);
if(!is_array($url))
{
// The image doesn't exist
}
else
{
// The image exists
}
这就是我所做的。它涵盖了获取标题的更多可能结果,因为如果您无法访问该文件,它并不总是“404未找到”。有时会出现“永久移动”、“禁止”和其他可能的消息。但是,如果文件存在并且可以访问,则只有“200 OK”。使用HTTP的部分可以有1.1或1.0,这就是为什么我只是使用strpos在任何情况下都更可靠
function remote_file_exists($file){
$url=getimagesize($file);
if(is_array($url))
{
return true;
}
else {
return false;
}
$file='http://www.site.com/pic.jpg';
echo remote_file_exists($file); // return true if found and if not found it will return false
图像文件的URL和服务器文件系统上同一图像文件的路径是两个不同的字符串。我被误导了,我浏览了其他文章,使用了文件为“存在”的远程路径。@Phil你用URL试过了吗?它返回false:如果服务器返回:HTTP/1.1 403?如果是403,则图像仍然不可访问,但仍然存在。是的,这可以工作,但John的答案更简单,不会因403或标头中的键入而失败。解决方案很好。要检查文件是否可访问,可以执行以下操作:
$file\u headers[0]!='HTTP/1.1 200 OK’
这非常昂贵。在检索信息之前,将下载整个图像。您最好只查看请求的标题。查看get_headers()@谢谢你!更新。这是一个极好的答案(带有标题)。但它是否总是在不同的服务器上返回相同的头?很抱歉我对此一无所知。或者您也可以使用curl并检查返回的http状态代码。如果是404,则远处的图像不存在。
if(@get_headers($your_url)[0] == 'HTTP/1.1 404 Not Found')
{
// The image doesn't exist
}
else
{
// The image exists
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) echo 'YES';
else echo 'NO';
function remote_file_exists($file){
$url=getimagesize($file);
if(is_array($url))
{
return true;
}
else {
return false;
}
$file='http://www.site.com/pic.jpg';
echo remote_file_exists($file); // return true if found and if not found it will return false
$file_headers = @get_headers( 'http://example.com/image.jpg' );
$is_the_file_accessable = true;
if( strpos( $file_headers[0], ' 200 OK' ) !== false ){
$is_the_file_accessable = false;
}
if( $is_the_file_accessable ){
// THE IMAGE CAN BE ACCESSED.
}
else
{
// THE IMAGE CANNOT BE ACCESSED.
}