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.

  • libcurl: A free and easy-to-use client-side URL transfer library, supporting FTP, TPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. libcurl supports TTPS certificates, HTTP POST, HTTP PUT, FTP uploading, kerberos, HTTP based upload, proxies, cookies, user & password authentication, file transfer resume, HTTP proxy tunneling and many more. libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported and fast.
  • curl: A command line tool for getting or sending files using URL syntax. Since curl uses libcurl, it supports a range of common internal protocols, currently including HTTP, HTTPS, FTP, FTPS, GOPHER, TELNET, DICT, and FILE.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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';
}
  
?>

chevron_right


Output:

Specified URL exists

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
  
?>

chevron_right


Output:

Specified URL exists


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.