© copyright 14.May.2008 by Paul Bradley filed under PHP
I recently developed a garage booking system which used the experian vehicle lookup interface, to retrieve the vehicles make, model, engine size and fuel type using the customers car registration number.
The experian service requires that a HTTP POST request is sent over an SSL connection, and returns the vehicle details as an XML feed. I have used fsockopen many times before to send GET requests to web services, but have never used the POST method, and never needed SSL before. At first it appeared that I would need to use the Curl module, but after some further reading discovered you could use the fsockopen function with SSL connections from version 4.3.0 onwards, when used in conjunction with OpenSSL.
You can check if your current PHP installation has OpenSSL installed by using the phpinfo command, as shown below.
<?php
// show just the module information.
phpinfo(INFO_MODULES);
?>
To use PHP with OpenSSL support you must compile PHP --with-openssl[=DIR], Windows users need to add the PHP directory to the windows PATH statement, and un-comment the extension=php_openssl.dll line in the PHP.INI file.
If your using shared hosting and your provider is unwilling to install OpenSSL, then I recommend changing to a more professional hosting company, like Pair Networks.
Once you have OpenSSL running within PHP, you can connect to a secure web site using port 443, and the url format of ssl://
Below is some conceptual code, which posts two form fields (REG and TRANSACTIONTYPE) using the x-www-form-urlencoded content type, to a page called index.php on the web site securesite.com. The data returned by that index.php page is then read into a variable called $_return, and printed out to the web browser.
<?php
$http_data = 'REG=K9 DDR';
$http_data .= '&TRANSACTIONTYPE=03';
$fp = fsockopen("ssl://www.securesite.com",
443, $errno, $errstr, 15);
if (!$fp) {
$_return = ' error: ' . $errno . ' ' . $errstr;
die $_return;
} else {
$http = "POST /index.php HTTP/1.1\r\n";
$http .= "Host: " . $_SERVER['HTTP_HOST'] . "\r\n";
$http .= "User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\r\n";
$http .= "Content-Type: application/x-www-form-urlencoded\r\n";
$http .= "Content-length: " . strlen($http_data) . "\r\n";
$http .= "Connection: close\r\n\r\n";
$http .= $http_data . "\r\n\r\n";
fwrite($fp, $http);
while (!feof($fp)) {
$_return .= fgets($fp, 4096);
}
fclose($fp);
echo $_return;
}
?>
About the Author
Paul Bradley is a VB.NET software developer living and working in Cumbria. He provides PHP & MySQL bespoke development services via his software development company, Carlisle Software Limited.
He has over 20 years programming experience.