要在 PHP 檢查某一個網址是否存在,可以使用 get_headers() 這個 function,並藉由其回傳的 status code 來判斷該網址是否正常。
範例:
$url = "https://tools.wingzero.tw/";
// Use get_headers() function
$headers = @get_headers($url);
// Use condition to check the existence of URL
// 檢查狀態碼是否是 200 不是 200 代表網址找不到東西
if ($headers && strpos($headers[0], '200')) {
$status = "URL Exist";
} else {
$status = "URL Doesn't Exist";
}
echo $status;
藉由這個判斷就可以在目標網址有問題時,即時顯示錯誤了。
參考:
Php Check If Url Exists With Code Examples