Open In App

How to test a URL for 404 error in PHP?

Last Updated : 20 May, 2019
Like Article

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.

// 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';


Specified URL exists

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

// Initializing new session
$ch = curl_init("");
// Request method is set
curl_setopt($ch, CURLOPT_NOBODY, true);
// Executing cURL session
// 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";


Specified URL exists

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads