Logo
Code Ranks ×

PHP cURL Part 3(Checking URL existence)|Coderank

08/04/2019  .   2 minutes, 9 seconds to read  .   Posted by Admin
#php #curl #phpcurl #learnphp #phpframework #phpcrud #phptutorial #phpcode #phpmagicfunctions #c#

So far, we've learned the following features of PHP cURL in this series of articles.

  1. PHP cURL Basics
  2. Getting Contents of any URL
  3. Downloading File from URL

In this article, we'll learn how to check if any URL exists or not(website availablity test). In many cases, we need to ask users to enter some reference URLs like when any user is registered for product marketing on their site, they need to give their website URL. We can verify correct URL format using regular expression but we also need to verify if this website actually exists on the internet or not.

In this case, PHP cURL comes in the role. We can use the following PHP code for URL verification.

$url = "https://www.coderanks.com";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);

if ($result !== false) {
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
    if ($status_code == 404) {
        echo "URL Not Exists"
    }else{
        echo "URL Exists";
    } 
}else{
    echo "URL not Exists";
}

To check any other URL, you can change the value of $url.

Code Explain:

Now let's explain how the above code will work. We've done a basic PHP cURL request with CURLOPT_NOBODY flag, which means we're not interested in the body(content) of the URL so don't return its body or content.

After executing cURL using curl_exec, we'll have its response in $result. If the response is false, it means the URL does n't exist. But sometimes, URL doesn't exist but still, the response is not false.

In that case, we need to check the HTTP status code of the URL. We've done that using as follows.

$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
if ($status_code == 404) {
    echo "URL Not Exists"
}else{
    echo "URL Exists";
} 

curl_getinfo():

curl_getinfo() function is used to get specific informations from cURL request. To get any information we need to pass cURL object and the constant for which we want to get info. Following are the commonly used constants.

  1. CURLINFO_HTTP_CODE: return last HTTP response code of the request.
  2. CURLINFO_FILETIME: return the time taken for the remote document retrieval.
  3. CURLINFO_CONNECT_TIME: time(seconds) taken for estiblishing connection.

For the full list of constants, you can check the curl_getinfo documentation(here).

in our case, curl_getinfo will return the last HTTP status code. If that code is 404(Not Found) then we can say URL is not existed otherwise URL exists.

That's all for this part of the article. In the next part, we'll learn how to submit any form using cURL.

Thanks for reading.