PHP检测源图像URL链接是否导致“断开"链接.图像? [英] PHP Detecting if source image url link leads to a "broken" image?

查看:147
本文介绍了PHP检测源图像URL链接是否导致“断开"链接.图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个缩略图生成器脚本,该脚本接受URL形式的源图像.有没有一种方法可以检测源URL是否损坏"-是否不存在或是否导致非图像文件?

Suppose you have a thumbnail generator script that accepts source images in the form of a URL. Is there a way to detect if the source URL is "broken" - whether nonexistent or leads to an non-image file?

使用getimagesize()或其他PHP GD函数进行暴力破解不是一个解决方案,因为可以输入欺骗性URL,这些URL可能根本不是图像(http://example.com/malicious.exe或同一文件,但重命名为http://example.com/malicious.jpg). -在必须调用GD之前,PHP可以很容易地检测到这种情况.我正在寻找GD预先消毒,然后让GD尝试其营来解析文件.

Just brute force using getimagesize() or another PHP GD function is not a solution, since spoofed stray URL's that might not be images at all (http://example.com/malicious.exe or the same file, but renamed as http://example.com/malicious.jpg) could be input - such cases could easily be detected by PHP before having to invoke GD. I'm looking for GD pre-sanitizing before having GD try its battalion at parsing the file.

第一步,以下正则表达式检查URL是否为图像扩展名: preg_match('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)([^\s]+(\.(?i)(jpg|png|gif|bmp))$)@', $txt,$url);

as a first step, the following regular expression checks if the URL is an image extension: preg_match('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)([^\s]+(\.(?i)(jpg|png|gif|bmp))$)@', $txt,$url);

推荐答案

在php中使用file_exists函数,您可以使用它检查网址.

use file_exists function in php, you can check urls with it.

请参阅下面的文档,显示如何检查img ...确切需要什么

See documentation below, shows how to check img... exactly what you need

文件已存在- http://www.php.net/manual/zh-CN/function.file-exists.php#93572

URL存在- http://www.php.net/manual/zh-CN/function.file-exists.php#85246

这里是替代代码,用于检查网址.如果要在浏览器中进行测试,请将\n替换为<br/>

Here is alternative code for checking the url. If you will test in browser replace \n with <br/>

<?php

$urls = array('http://www.google.com/images/logos/ps_logo2.png', 'http://www.google.com/images/logos/ps_logo2_not_exists.png');

foreach($urls as $url){
   echo "$url - ";
   echo url_exists($url) ? "Exists" : 'Not Exists';
   echo "\n\n";
}


function url_exists($url) {
    $hdrs = @get_headers($url);

    echo @$hdrs[1]."\n";

    return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
}
?>

输出如下

http://www.google.com/images/logos/ps_logo2.png - Content-Type: image/png
Exists

http://www.google.com/images/logos/ps_logo2_not_exists.png - Content-Type: text/html; charset=UTF-8
Not Exists

这篇关于PHP检测源图像URL链接是否导致“断开"链接.图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆