Web Development

Check URL Existence with PHP

PHP URL Existence

In this article we will see how to Check URL Existence with PHP. Here existence means we are checking content which we are requesting is available on server or not.

We can check the existence of URL in two ways using PHP. First one is the [code]get_header[/code] function and second one is [code]CURL[/code].

[gads]

PHP URL Existence

Basically we are checking HTTP header of the URL and based on that we can determine existence of the url. 200 Code stands for OK header and 404 stands for Not Found.
Let’s get into both of the methods.

get_headers Function

Using this get_headers function we can get the HTTP header information of the given URL.

[cc lang=”php”]
$url = “http://www.domain.com/demo.jpg”;
$headers = @get_headers($url);
if(strpos($headers[0],’404′) === false)
{
echo “URL Exists”;
}
else
{
echo “URL Not Exists”;
}
[/cc]

[gads]

Note: If you set second parameter of the get_headers() to true then you will get result in associative array. Just try for it.

cURL

[cc lang=”php”]
$url = “http://www.domain.com/demo.jpg”;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
if ($result !== false)
{
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 404)
{
echo “URL Not Exists”
}
else
{
echo “URL Exists”;
}
}
else
{
echo “URL not Exists”;
}
[/cc]

[gads]

Note: We have used CURLOPT_NOBODY to just check for the connection and not to fetch whole body.

So we are done with the checking the existence of the URL with PHP, share your views/comments/suggestions.

Shares:
  • kkatusic
    kkatusic
    May 15, 2013 at 2:23 am

    Nice tips

    Reply
  • pavan bangaram
    pavan bangaram
    December 20, 2019 at 2:54 pm

    Good information provided regarding URL existence in PHP..Than x.!

    Reply
  • Dan
    Dan
    October 27, 2015 at 2:15 am

    Thanks for the info. You are missing a semicolon after the echo here.

    if ($statusCode == 404)
    {
    echo “URL Not Exists”
    }

    Reply
  • Michal Zielinski
    Michal Zielinski
    February 2, 2018 at 6:26 pm

    in cURL example u forgot
    if ($statusCode == 404)

    {

    echo “URL Not Exists” <---- ";" :)

    Reply

Leave a Reply

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