I'm writing a script which checks an array of domain names using curl and returns their http codes.
$urls = array('http://www.example.com', 'http://www.example2.com', 'http://www.example3.com');
$msg = "
<p><strong>URL Error Check</strong></p>
";
//Set code colours
$code200 = '<span style="color: green;"> OK - ';
$code0 = '<span style="color: red;"> Undefined Error - ';
$code404 = '<span style="color: red;"> File Not Found - ';
foreach($urls as $value){
$ch = curl_init($value);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_CERTINFO,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpcode==301 || $httpcode==302){
$redirect = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
$httpcode .='<br> Redirects to: <span style="color: orange;">'.$redirect;
}
curl_close($ch);
$msg .= $value.": <strong>".${code.$httpcode}.$httpcode."</strong></span><br><br>";
}
echo $msg;
When the code is 301 or 302 it returns the resolving url after the redirect. I'd like it to then check the final URL and return it's http code as well.
Can someone please suggest how I can do this?
you can use this option for your curl-request:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
With this option set to true, your request will not stop when a redirect occurs.