PHP中怎么检测链接是否存在

PHP中怎么检测链接是否存在,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

1) 使用get_headers: 
 

 <?php 

$url = "https://cache..com/upload/information/20201209/266/40575.jpg"; 
$headers = @get_headers($url); 
if($headers[0] == 'HTTP/1.1 404 Not Found') 
{ 
 echo "URL not Exists"; 
} 
else 
{ 
 echo "URL Exists"; 
} 
?>

  get_headers中有第2个参数,是true的话,结果将会是个关联数组

2) 使用CURL 

  <?php 
$url = "http://www.domain.com/demo.jpg"; 
$curl = curl_init($url); 
curl_setopt($curl, CURLOPT_NOBODY, true); 
$result = curl_exec($curl); 
if ($result !== false) 
{ 
 $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
 if ($statusCode == 200) 
 { 
 echo "URL Exists" 
 } 

} 
else 
{ 
 echo "URL not Exists"; 
} 
?>

  CURLOPT_NOBODY指定了只是建立连接,而不取整个报文的内容

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。