http.header Home



Home | Http protocol | Coding references | Apache 1.3 | FAQ | About | Français


All coding languages provide ways to make an http transaction.
There are two things to know :

   1 - An transaction can be long, be careful with timeouts !
   2 - There is always a packaged way to do it, depend on your needs...

In this section, I present sample http request in PHP and Perl.


Perl script

1 - The packaged way : use of LWP package

   use LWP::UserAgent;

   $Server = "www.yahoo.fr";
   $Port = "80";
   $File = "/the_file.gif";
   $Request = "http://$Server:$Port$File";

   my $User_Agent = new LWP::UserAgent;
   my $response = $User_Agent->get($Request);
   if ($response->is_success)
     { print $response->content; }
   else
     { print $response->status_line; };

2 - The manual way : open a socket and send an http request

Exemple to come !

3 - Complete sample application with Perl TK !

You can download for free my sample application "
HTTP tool", which includes example of perl TK and http client file upload via POST method. Screenshot.


Php script

1 - The packaged way : use of function fopen

Using the "fopen" function, you can open a file through an http connection.
Nothing to do ! Be careful with PHP version prior to 4.0.5 which do not handle redirects.
Note : it works through firewall and you can also use ftp ! Exemple :

<?php
   $fp1 = fopen("http://www.google.com/", "r" );
   $fp2 = fopen("http://www.yahoo.com", "r", "8080" );
?>

 

    In this page

Perl samples
Php samples

      External links

Perl :
> Web Client Programming with Perl by O'Reilly

> Perl & LWP by O'Reilly




 
2 - The manual way : open a socket and send an http request

Exemple, getting "http://www.yahoo.fr/the_file.gif :

<?php
   $Server = "www.yahoo.fr";
   $Port = "80";
   $File = "/the_file.gif";
   $Request = "GET " . $File . " HTTP/1.0\r\n";
   $Request = $Request . "Host: " . $Server . "\r\n";         // Add attributs you want
   $Request = $Request . "\r\n";                                   // Ending by an empty line
   
   $Socket = fsockopen($Server, $Port, &$errno, &$errstr, 30);
   if(!$Socket) Error("<b>Can't connect host</b><br>$errstr ($errno)");
   
   fputs($Socket, $Request);
   
   while( ! ereg( "^\r?\n?$", $Line ) )                            // Getting head content
       $Head = $Head . fgets($Socket, 1024);
   
   while(!feof($Socket))                                             // Getting file content
       $Html = $Html . fgets($Socket, 1024);
   
   fclose($Socket);
?>

 




Matthieu Delgrange 2006 - http.header@netcourrier.com - Home