我在一个表中存储了数千个图像url,每行一个。问题是它们中的一些具有带有空格,重音字符等的格式错误的名称,例如:
https://www.greatsite.com/upload/memdocs/111046-carte d'identit� 001-072716141540.jpg
在浏览器中打开此url时,输出如下错误:
Not Found
The requested URL /upload/memdocs/111046-carte d'identit� 001-072716141540.jpg was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
我需要以编程方式找到抛出此"Not Found"错误的所有图像url(为了以后正确格式化图像url名称)。
到目前为止,我试图使用getimagesize()和file_get_contents(),但没有运气。getimagesize()并不总是有效,因为我认为它修复了图像名称,因为对于上面的url,它实际上返回了图像信息数组。file_get_contents()总是返回一些东西,不管图像url是否抛出"Not Found"错误。
有什么建议吗?我希望我说得有道理。由于
您可以从DB获取所有图像并使用foreach对它们进行迭代。在foreach中尝试检查文件是否存在。例子:
foreach ($images as $image) {
$valid = is_file($imageDir.$image->path);
}
is_file是检查文件是否存在的最佳方法。File_get_contents将读取整个文件,速度较慢。
或者你可以在图像路径上执行regex:
foreach ($images as $image) {
$valid = preg_match('/[0-9a-zA-Z'$-_'.'+!'*''('),];'/'?':'@='&/', $image->path);
}
我不是100%肯定,如果这个正则表达式将正确验证所有的url ....但是大多数。
你应该得到报头做web请求:
foreach ($images as $image) {
$url = 'https://www.greatsite.com/'.$image;
$file_headers = @get_headers($url);
if($file_headers && $file_headers[0] == 'HTTP/1.1 404 Not Found') {
// URL Not Found do something to log it
}
}
还有很多其他的方法,使用CURL等,但我发现这是最简单的