Skip to content
Related Articles

Related Articles

How to test a URL for 404 error in PHP?
  • Last Updated : 20 May, 2019
GeeksforGeeks - Summer Carnival Banner

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.




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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :