php - 如果图像无效,检查图像是否存在需要很长时间
问题描述
我有一个功能可以检查图像是否有效,以及是否在屏幕上打印 img。
<?php
function isImage($url){
$url_headers=get_headers($url, 1);
if($url_headers[0] == 'HTTP/1.1 404 Not Found') {
$url_exists = false;
}
else {
$url_exists = true;
}
if($url_exists){
if(isset($url_headers['Content-Type'])){
$type=strtolower($url_headers['Content-Type']);
$valid_image_type=array();
$valid_image_type['image/png']='';
$valid_image_type['image/jpg']='';
$valid_image_type['image/jpeg']='';
$valid_image_type['image/jpe']='';
$valid_image_type['image/gif']='';
if(isset($valid_image_type[$type])){
return true;
}
else{
return false;
}
}
}
}
if(isImage("http://curiosidadeslegais.org/wp-content/uploads/2016/08/zuera-pa-w5app.jpg")){
echo '<img src="http://curiosidadeslegais.org/wp-content/uploads/2016/08/zuera-pa-w5app.jpg" alt="">';
}
问题是我不知道为什么页面在上面的 url 中花了这么长时间。图像不再存在。和 html 打印:
<html>
<head>
<meta name="robots" content="noarchive" />
<meta name="googlebot" content="nosnippet" />
</head>
<body>
<div align=center>
<h3>Error. Page cannot be displayed. Please contact your service provider for more details. (9)</h3>
</div>
</body>
</html>
我不知道为什么我的功能需要很长时间才能验证它不是图像并忽略它。任何想法为什么?
检查图像是否存在或不打印应该很快。但在这种情况下,它需要很长时间。
解决方案
file_get_contents 可以返回标头并设置最大超时。
$options = stream_context_create(array('http'=>
array(
"timeout" => 1, // one second
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
));
$url_headers = file_get_contents($url, false, $options);
这是未经测试的,因为我正在手机上打字。
我在您的代码中注意到的另一件事是$url_exists = true;
为什么?为什么不将下面的代码向上移动,并将上面的行替换为if($url_exists == true)
.
这不是代码缓慢的原因,但完全没有必要。
推荐阅读
- apache-spark - 如何从 Spark 结构化流作业中的每个微批次中的相同起始偏移量读取?
- .net - 如何将“dotnet restore”与需要进行身份验证的提要一起使用?
- xml - DB2 存储过程优化器未使用最有效的索引
- python - 将 Python 项目提交到 Dataproc 作业
- javascript - 检查字符串中的单词是否与数组中的单词匹配,如果匹配则将其从字符串中删除
- javascript - 否则,角度选择类
- python - Python解析xml找不到元素
- ios - 当应用程序在后台时,我可以访问 AppDelegate 内的应用程序变量吗?
- antlr4 - ANTLR4 空格问题,将数字与字母分开
- python - 具有混合 dtypes 的 pandas DataFrame 的类型提示