How to test a URL for 404 error in PHP?
Last Updated :
20 May, 2019
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
$array = @get_headers( $url );
$string = $array [0];
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
curl_setopt( $ch , CURLOPT_NOBODY, true);
curl_exec( $ch );
$retcode = curl_getinfo( $ch , CURLINFO_HTTP_CODE);
if ( $retcode != 200) {
echo "Specified URL does not exist" ;
}
else {
echo "Specified URL exists" ;
}
curl_close( $ch );
?>
|
Output:
Specified URL exists
Share your thoughts in the comments
Please Login to comment...