Oct 02
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.




Publié le 02/10/2008 à 9:47
ta variable $status ne devrait elle pas s’appeler $status_code ?
Publié le 02/10/2008 à 17:16
Si
Merci pour la correction, c’est corrigé.