Open In App

How to test a URL for 404 error in PHP?

Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library.

cURL: The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl.



Example 1: This example test a URL for 404 error without using cURL approach.




<?php
  
// Creating a variable with an URL
// to be checked
  
// Getting page header data
$array = @get_headers($url);
  
// Storing value at 1st position because
// that is only what we need to check
$string = $array[0];
  
// 404 for error, 200 for no error
if(strpos($string, "200")) {
    echo 'Specified URL Exists';
else {
    echo 'Specified URL does not exist';
}
  
?>

Output:



Specified URL exists

Example 2: This example test a URL for 404 error using cURL approach.




<?php
  
// Initializing new session
$ch = curl_init("https://www.geeksforgeeks.org");
  
// Request method is set
curl_setopt($ch, CURLOPT_NOBODY, true);
  
// Executing cURL session
curl_exec($ch);
  
// Getting information about HTTP Code
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  
// Testing for 404 Error
if($retcode != 200) {
    echo "Specified URL does not exist";
}
else {
    echo "Specified URL exists";
}
  
curl_close($ch);
  
?>

Output:

Specified URL exists

Article Tags :