Create HTTPs request with phpWebrequest

I received several emails about my phpWebRequest php class, asking how we can create HTTPs POST request. Before I answer this I think it’s important to understant the HTTP authentication mechanism.

There are 2 kinds of authentication: Basic and Digest. I gonna describe only Basic since it’s very is to use in the phpWebRequest class.

Basic is the easiest authentication to setup, since it do not provide any encryption during the transmission of the HTTP request.
Here is what happens when you try to reach a secured page (on https://a.server.com/the/secure/page.dll)

Client:
GET /the/secure/page.dll HTTP/1.1
Server:
HTTP/1.1 401 Authorization Required
WWW-Authenticate: Basice realm="Basic Realm"

In the answer we have from the server, we can see that a Basic authentication is required. That means in our HTTP header we need to add a field called Authorization that contains the login and password to reach the secured page. In our case the login is myLogin and the password is myPasswrd . The new Authorization field value will be myLogin:myPasswd encoded as a base64 string so bXlMb2dpbjpteVBhc3N3ZCA=
We can now try to reach the page :

Client:
GET /the/secure/page.dll HTTP/1.1
Authorization: Basic bXlMb2dpbjpteVBhc3N3ZCA=
Server:
HTTP/1.1 200

Here is how to do that with the phpWebRequest class:

<?php
require_once('phpWebRequest.class.php');

$XMLString = '<?xml version="1.0" encoding="UTF-8"?><root><elems><e1>Element1</e1></elems></root>';

$rq = new PhpWebRequest();
$passwd =base64_encode("myLogin:myPasswd") ;

$rq->InitServer("256.256.256.256","/the/secure/page.dll");

$strSize = $rq->DataReaderFactory($XMLString);

$rq->InitRequest("POST");

$headerElements = array("Host" => "256.256.256.256",
						"Authorization" => "Basic ".$passwd,
                        "Connection" => "Close",
                        "Content-type" => "multipart/mixed",
                        "Content-length" => $strSize
                        );

$rq->CfgHeader($headerElements);

if($rq->SendRequest()){
    echo "Request sent !";
}
else{
    echo "ERROR";
}

?>

You can also have a look to the RFC2617 for more details on Basic and Digest.

Advertisements

One Response

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: