#native_company# #native_desc#
#native_cta#

Using Perl in PHP to process HTTP requests

By Nicholas LaDieu
on November 25, 2000

The Problem:

I needed a script in PHP which would get information from UPS (http://www.ec.ups.com/) via a server HTTP request and then get the HTTP stream back into a variable. This data was then parsed and integrated seemlessly into an e-commmerce project so that I could provide dynamic shipping quotes on my products right from UPS.

Option 1:

I first when to PHP.net and looked for a quick solution. I ran into CURL (http://www.php.net/manual/ref.curl.php), but alas I couln’t figure out how to install it, much less use it.

The Hack:

First I downloaded HTTP:Lite perl module from CPAN (http://theoryx5.uwinnipeg.ca/CPAN/data/HTTP-Lite/Lite.html). Simply put the .pm file into the same directory as you are going to put your perl script.
I then wrote the following PERL snippet


#!/usr/bin/perl

    require("Lite.pm");

	#print $ARGV[0];

    $http = new HTTP::Lite;
	   $req = $http->request($ARGV[0])
        or die "Unable to get document: $!";
    die "Request failed ($req): ".$http->status_message()
      if $req ne "200";
    @headers = $http->headers_array();
    $body = $http->body();
    #foreach $header (@headers)
    #{
    #  print "$header$CRLF";
    #}
    print "$CRLF";
    print "$body$CRLF";

PHP- Now anytime I want to process an HTTP request in my PHP pages I simply say:


<?php
   $str= `perl getpage.pl "http://www.yahoo.com/"`

  // NOTE: those are backticks NOT single quotes!!
?>

Its also noteable to mention that you can get the contents of any unix command with the backtick operators, just like in perl! This can be useful to list files in directories or do file operations without the hassle!