有什么更好的方法可以检查是否存在外部托管的图像文件



我使用下面的代码,它对我有效,但我们大多数人都知道我们不能信任fopen,因为它在外部文件上并不总是很好地工作。所以我的问题是,我还可以用什么方法来检查是否存在外部url?

我知道这可以用cURL完成,我可以检查图像大小,但我想知道其他编码器如何解决这个问题,以及最好的方法是什么。

必需:如果图像可用,则回显图像代码;如果图像不可用,则如下面的工作示例所示回显文本链接代码。

<?php
// Set the beyondsecurity.com image URL you want to connect to...
$url = "https://secure.beyondsecurity.com/verification-images/www.largevideotube.com/vulnerability-scanner-2.gif";
// Check to see if the beyondsecurity.com image URL exists by trying to open it for read only..
if (fopen($url, "r")) {
// echo the beyondsecurity.com image link if I was able to open the beyondsecurity.com image URL for read only..
echo '<a href="http://www.beyondsecurity.com/vulnerability-scanner-verification/www.largevideotube.com"><img src="https://secure.beyondsecurity.com/verification-images/www.largevideotube.com/vulnerability-scanner-2.gif" alt="Website Security Test" /></a>';
} else {
// echo a text link if it took to many time to open the file or if it wasn't there at all..
echo '<a href="http://www.beyondsecurity.com/vulnerability-scanner-verification/www.largevideotube.com">Website Security Test</a>';
}
?>

我会发出HTTP请求,并检查响应状态代码和响应标头。如果你得到200的回复,那就意味着你的请求是可以的。您可以检查"内容类型"标头以查看内容是否为图像。然后你可以对响应体做任何你想做的事情,对于200个响应来说,它就是图像。如果您得到4XX或5XX的响应,则表示出现问题或找不到图像。你可以用cURL,或者像Guzzle这样制作HTTP请求/响应的很棒的库来实现这一点。

最新更新