Created
February 16, 2017 13:08
-
-
Save domsie/a788ffcc79e27ac1ba6477599a3e95db to your computer and use it in GitHub Desktop.
Check if the given URL is reachable with php && curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Check if the URL is reachable. | |
* | |
* @param string $url | |
* The URL to check. | |
* @return this | |
* @throws \LogicException | |
*/ | |
public function checkReachability($url) { | |
$ch = curl_init($url); | |
curl_setopt_array($ch, [ | |
CURLOPT_AUTOREFERER => true, | |
CURLOPT_CONNECTTIMEOUT => 5, | |
CURLOPT_ENCODING => "", | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_MAXREDIRS => 1, | |
CURLOPT_NOBODY => true, | |
CURLOPT_SSL_VERIFYHOST => false, | |
CURLOPT_SSL_VERIFYPEER => false, | |
CURLOPT_TIMEOUT => 5, | |
// It's very important to let other webmasters know who's probing their servers. | |
CURLOPT_USERAGENT => "Mozilla/5.0 (compatible; StackOverflow/0.0.1; +https://codereview.stackexchange.com/)", | |
]); | |
curl_exec($ch); | |
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
curl_close($ch); | |
if ($code !== 200) { | |
throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable)."); | |
} | |
return $this; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment