Search This Blog

Friday, June 5, 2009

PHP call external cgi and process responses

This is tough for me. First time to code in PHP with cgi and don't know how to start. Thanks google for this.

My task is call a cgi script to execute some function and process the return data. Well, here i'll mention on how to call external cgi and the process part can be settled using PHP string processing.

Let's start by example:

cgi domain location: www.xincube.com/script/handler/api.cgi

The code will strip header below and return the content of the response data.

HTTP/1.1 200 OK
Date: Sat, 06 Jun 2009 02:23:33 GMT
Server: Apache
Proxy-x-forwarded-for: 203.116.10.206
X-returncode: 0
X-returndesc: Access denied
Cache-control: no-cache
Pragma: no-cache
Connection: close
Transfer-Encoding: chunked
Content-Type: text/plain

We can do anything we want to get the information we need in $content.

CODE:

/* sample for calling cgi */
$host = 'www.xincube.com';
$path = '/scripts/handler/API.cgi';

$data_to_send = 'action=GetSupportedData';


PostToHost($host, $path, $data_to_send);

/* function that will call cgi */
function PostToHost($host, $path, $data_to_send) {

$header = "not yet";
$content = '';
$fp = fsockopen($host,80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)\n";
}
else {
fputs($fp, "POST $path HTTP/1.1\n");
fputs($fp, "Host: $host\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
fputs($fp, "Content-length: ".strlen($data_to_send)."\n");
fputs($fp, "Connection: close\n\n");
fputs($fp, $data_to_send);

while(!feof($fp)) {
//echo fgets($fp, 4000);
$line = fgets( $fp, 4000 );
if( $line == "\r\n" && $header == "not yet" ) {
$header = "passed";
}
if( $header == "passed" ) {
$content .= $line;
}
}
echo $content;
fclose($fp);
}
}


Hope this help. Support me to write more by clicking on the ads sponsor or donation. Thanks

1 comment:

Shai said...

Thank you a billion times over. I've spent the last two weeks trying to achieve exactly this!
I've tried exec(), system(), nothing worked as I had to pass arguments to the CGI script. Thank you again for taking the time to post this!

I hope you don't mind, I've reposted this on my blog shaiperednik.com/blog.


Thank you Again