gpt4 book ai didi

PHP 检测源图像 url 链接是否指向 "broken"图像?

转载 作者:IT王子 更新时间:2023-10-29 00:03:44 24 4
gpt4 key购买 nike

假设您有一个缩略图生成器脚本,它接受 URL 形式的源图像。有没有办法检测源 URL 是否“损坏”- 是否不存在或导致非图像文件?


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


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

最佳答案

使用file_exists在 php 中的函数,你可以用它检查 url。

请参阅下面的文档,展示如何检查 img...正是您所需要的

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

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


这里是 alternative code用于检查网址。如果您将在浏览器中进行测试,请替换 \n<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 链接是否指向 "broken"图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3677965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com