Facebook LinkedIn SourceForge Twitter RSS LastFM
logologo

Récupérer les en-têtes HTTP en PHP avec la lib cURL

Geoffray Warnants|13/12/2008|21 commentaires

Voulant une fois pour toutes pouvoir gérer correctement les appels à des pages distantes via HTTP, j'ai décidé de me pencher sur la librairie cURL. Une des premières étapes que je souhaitais accomplir était d'extraire les en-têtes HTTP afin d'obtenir une indication sur le déroulement de la requête HTTP demandée. Une première approche permet de réaliser ceci très simplement grâce à l'option de transmission CURLOPT_HEADER :

<?php
$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://www.google.com');
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_HEADER, true);

$page = curl_exec($url);
curl_close($url);
?>

L'inconvénient majeur de cette méthode est que les en-têtes HTTP et le contenu de la page demandée se retrouvent concaténés dans le résultat de curl_exec(). Effectuer une décomposition manuelle du résultat obtenu pourrait fournir le résultat attendu, mais c'est alors omettre une solution plus propre offerte par la librairie. Elle propose en effet un mécanisme de fonctions "callbacks" appelées lorsqu'un évènement particulier se produit. Dans le cas qui nous intéresse ici, l'option CURLOPT_HEADERFUNCTION permet d'appeler une fonction à chaque en-tête HTTP rencontré. Attention que cette fonction doit absolument retourner le nombre d'octets de l'en-tête reçu en paramètre.

<?php
function read_header($url, $str) {
    echo 'Header : '.$str."\n";
    return strlen($str);
}

$url = curl_init();
curl_setopt($url, CURLOPT_URL, 'http://www.google.com');
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_HEADER, true);
curl_setopt($url, CURLOPT_HEADERFUNCTION, 'read_header');

$page = curl_exec($url);
curl_close($url);
?>

Sur base de ce principe, on peut alors se construire rapidement une petit classe, histoire d'encapsuler ces traitements dans un objet :

<?php
/**
 * A sample class to read HTTP headers
 * @author Geoffray Warnants - http://www.geoffray.be
 */
class HTTPReader {
    protected $_url = null;
    protected $_headers = array();
    protected $_body = '';
    
    public function __construct($url) {
        $this->_url = curl_init($url);   
        curl_setopt($this->_url, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->_url, CURLOPT_HEADER, true);
        curl_setopt($this->_url, CURLOPT_HEADERFUNCTION,
            array($this, 'readHeaders')
        );
    }
    public function __destruct() {
        curl_close($this->_url);
    }
    public function getHeaders() {
        $this->_body = curl_exec($this->_url);
        return $this->_headers;
    }
    public function getBody() {
        return $this->_body;
    }
    protected function readHeaders($url, $str) {
        if (strlen($str) > 0) {
            $this->_headers[] = $str;
        }
        return strlen($str);
    }
}
?>

<<< Retour

Vos commentaires

19 commentaires postés

seo services marketplace
15/05/2026 07:54Posté par seo services marketplace
Hi there everyone, it's my first go to see at this web site, and article is really fruitful in support of me, keep
up posting these articles.
??t hoa t??i online giao nhanh
12/05/2026 06:58Posté par ??t hoa t??i online giao nhanh
When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get three e-mails with the same comment.
Is there any way you can remove people from that service?
Many thanks!
https://tiemhoachieu.com/
10/05/2026 22:39Posté par https://tiemhoachieu.com/
What's up Dear, are you truly visiting this website on a regular basis,
if so after that you will absolutely obtain fastidious experience.
seo backlinks
08/05/2026 20:36Posté par seo backlinks
What's up, the whole thing is going fine here and ofcourse every one is sharing information, that's actually fine, keep up writing.
??t hoa
05/05/2026 13:56Posté par ??t hoa
Piece of writing writing is also a fun, if you know afterward you can write if not it is complex to write.
seo services marketplace
04/05/2026 23:50Posté par seo services marketplace
Wow, incredible blog layout! How long have you been blogging for?you made blogging look easy.
The overall look of your website is great, let alone the content!
c?a h?ng hoa g?n ?
04/05/2026 07:45Posté par c?a h?ng hoa g?n ?
This design is steller! You obviously know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to
start my own blog (well, almost...HaHa!) Wonderful job.

I really loved what you had to say, and more than that,
how you presented it. Too cool!
ti?m hoa t??i giao nhanh
01/05/2026 22:49Posté par ti?m hoa t??i giao nhanh
Hi there to all, how is all, I think every one is getting more from this web site, and
your views are pleasant for new people.
Maurice
28/04/2026 11:54Posté par Maurice
Heya i'm for the first time here. I came across this
board and I find It really useful & it helped me out much.
I hope to give something back and help others like
you helped me.
tiemhoachieu.com
20/04/2026 03:12Posté par tiemhoachieu.com
Hello everyone, it's my first pay a visit at this site, and article is actually fruitful in support of me,
keep up posting such content.
gi? hoa
17/03/2026 22:07Posté par gi? hoa
Excellent article. I certainly love this website.
Continue the good work!
f4b1
12/09/2016 10:08Posté par f4b1
Merci pour cette astuce, j'étais justement en train de chercher comment faire et je suis tombé sur ton article, simple et clair !
Aurélien
19/04/2013 14:17Posté par Aurélien
Pratique.

A bookmarquer.

PS : merci Seebz et Charles pour les compléments.
gilles
08/09/2011 15:45Posté par gilles
Cool!!! Enfin un exemple qui ne nous fait pas passer par Mars pour obtenir le résultat voulu ;)
NICKEL
Charles
10/02/2011 01:54Posté par Charles
Seebz a raison, faisons simple :

file_get_contents("http://www.mapage.fr");
foreach ($http_response_header as $i)
{
echo '<br>'.$i ;
}
Seebz
10/11/2010 22:53Posté par Seebz
Une méthode plus simple est d'utiliser la variable prédéfinie `$http_response_header`

Exemple :

<?php file_get_contents("http://example.com");
var_dump($http_response_header);
Thera
03/08/2010 16:59Posté par Thera
Exactement ce que je cherchais et avec un exemple clair et simple en plus, parfait :)
Guillaume
11/02/2010 18:42Posté par Guillaume
Merci, ca m'a bien aidé !
joshua
14/01/2009 10:18Posté par joshua
c koi ton blog on y compren ke dal

Réagir à cet article

*


(Ne sera pas publiée, servira uniquement à afficher votre gravatar)


(Lien en dur et dofollow)

zend framework