Petit mémo pour aller chercher l’entête d’une page (headers) et seulement l’entête.
Expression régulière pour le code HTTP de la page, puis détéction de la nouvelle url si code 301.
$url = "http://maboite.org/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'MyUserAgent');
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$headers = curl_exec($ch);
$CurlErr = curl_error($ch);
curl_close($ch);
if ($CurlErr){
$status_code = '404';
}
else{
# get the status code before downloading the page content
preg_match("|^HTTP/1\.[0-9]\s([1-5][01][0-9])\s.*$|isU", $headers, $temp);
$status_code = $temp[1];
}
# if the page has moved, we get the new url
if($status_code == 301){
preg_match('/\s?[lL]ocation\s?:\s?(.*)\s/',$headers, $temp);
$url = $temp[1];
}
Pour info, curl est LA meilleur solution pour aller chercher une page sur un serveur distant. file_get_contents et autres fopen ne gèrent pas bien le timeout.
\\ tags: entêtes html, get headers

