How to validate link/url in PHP

How to validate link in php?

There is no simple method in PHP that validates whether a link is broken or not. There are functions available in php that can verify the url format and can detect malformed uri but to verify the resource we need to use curl or get_headers.

In this post, I am going to focus on validating the link using cURL.

Before we use cURL, we need to ensure that cURL extension is installed and enabled in PHP. For more information on installation, have a look at here. You can verify the installation on Linux by this command php -m | grep curl

As it is common validation requirement, Its a good idea to put it in Utils or Commons

Class Util
{
    /**
     * Validates the given Link is broken or not
     *
     * Prerequisite
     *  - cUrl
     *
     * Conditions:
     *  - Valid if HTTP Status in (200,301, 302, 303, 307)

     *  @author Mukesh Sharma
     *
     *  @return mixed Http Code If Valid Else False
     */
    static public function isValidLink($link)
    {
        $ch = curl_init($link);

        curl_setopt($ch,  CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,  CURLOPT_HEADER, TRUE); // Include the headers
        curl_setopt($ch,  CURLOPT_NOBODY, TRUE); // Make HEAD request

        $response = curl_exec($ch);

        if ( $response === false ){
            // something went wrong, assume not valid
            return false;
        }

        $http_code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (in_array($http_code, array(200, 301, 302, 303, 307)) === false) {
            // not a valid http code to asume success, link is not valid
            return false;
        }

        curl_close($ch); 

        return $http_code;
    }
}

Instead of http_code we can also return true, just in case we want a boolean return type.

One thought on “How to validate link/url in PHP

Leave a Reply

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