Call CGI from a PHP script
Uncategorized July 29th, 2009 by Shai Perednik
I’ve tried everything I can think of to get to call a CGI script from my PHP script.
exec() works, however I couldn’t figure out how to pass argumnts to the cgi script!
I found a blog post @ dotnetfish that provides sample code that works right out of the box!
Here’s an excerpt
/* 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);
}
}
