Last updated on February 2nd, 2022 at 07:42 am

PHP Check whether URL exists with CURL

This script helps us to check whether a URL exist or not by checking the header details.Here we are also displaying the output of the URL header details for further reference.

You might also be interested in this tutorial Get Web Page Content Using PHP CURL

Complete Code

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://mistonline.in/wp/");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
?>

Sample output

HTTP/1.1 200 OK Date: Fri, 04 Jan 2013 14:25:55 GMT Server: Apache X-Powered-By: PHP/5.3.1 Content-Type: text/html

You may need to write some logic to extract the response code to make sure that the website exists. In the above sample output we see 200, that means a OK success status response.

If you are getting this error below

PHP Fatal error:  Uncaught Error: Call to undefined function curl_init() in check_curl.php:2

You may need to install php-curl, in my case I am using Ubuntu.

sudo apt-get install php-curl

After installing, restart php-fpm (if you are using that) or restart Apache / Nginx (may be) to refresh the configuration. Then try hitting the URL again.

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *