Skip to content

Instantly share code, notes, and snippets.

@avataru
Created April 15, 2015 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avataru/47646e059c25da4ff74e to your computer and use it in GitHub Desktop.
Save avataru/47646e059c25da4ff74e to your computer and use it in GitHub Desktop.
Check link validity
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
* @url http://www.codezuzu.com/2015/03/how-to-validate-linkurl-in-php/
*
* @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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment