HTTP POST from PHP

Curl

Sometimes it can be useful to do a HTTP GET or HTTP POST request from a PHP script. I used to use curl to do this but there’s a ‘cleaner’ way to do this.

For reference, this is how to do the HTTP POST request in curl from PHP

$post_url = "http://myserver.ckers.be/redirect.php";
$parameter_string = "";
$parameter = array(
      'username' => urlencode( 'robby' ),
      'client' => urlencode( 'computer' ),
      'secret' => urlencode( 'password' ));
foreach($parameter as $key=>$value) {
  if (!($parameter_string=="")) $parameter_string .= "&";
  $parameter_string .= $key.'='.$value.'&'; 
}
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$post_url);
curl_setopt($ch,CURLOPT_POST,count($parameter));
curl_setopt($ch,CURLOPT_POSTFIELDS,$parameter_string);
$result = curl_exec($ch);

PEAR and HTTP_Request2

The PEAR – PHP Extension and Application Repository contains a number of useful reusable PHP components.

The component we are going to use is HTTP_Request2. You will need to have PHP and PEAR installed. It also depends on the Net_URL2 library but this library gets installed automatically.

sudo pear install HTTP_Request2
downloading HTTP_Request2-2.2.0.tgz ...
Starting to download HTTP_Request2-2.2.0.tgz (108,788 bytes)
.........................done: 108,788 bytes
downloading Net_URL2-2.0.5.tgz ...
Starting to download Net_URL2-2.0.5.tgz (17,456 bytes)
...done: 17,456 bytes
install ok: channel://pear.php.net/Net_URL2-2.0.5
install ok: channel://pear.php.net/HTTP_Request2-2.2.0

Depending on the umask that you use on your system might have to check the file read permissions. You have to make sure that the web server is able to read the files that are installed. This means that they need to have read permissions for everyone or for the web server user.
You can check the content of the package (the installed files) with

pear list-files HTTP_Request2

Most often the files are installed in /usr/share/php/. Check the proper permissions for HTTP and HTTP/Request2.

drwxr-xr-x 4 root root  4096 2014-01-14 18:41 Request2
-rw-r--r-- 1 root root 38335 2014-01-14 18:41 Request2.php

HTTP POST from PHP

The usage of the library is straightforward. First you have to include the library, build a request, add parameters and send the request.

require_once 'HTTP/Request2.php';
$post_url = "http://myserver.ckers.be/redirect.php";
$request = new HTTP_Request2($post_url);
$request->setMethod(HTTP_Request2::METHOD_POST)
    ->addPostParameter('username', 'robby' )
    ->addPostParameter(
        array(
          'client' => 'computer',
          'secret' => 'password'
    ));
$result = $request->send()->getBody();

The class has a long list of interesting methods, not only restricted to GET or POST requests.

Leave a Reply

Your email address will not be published. Required fields are marked *