Wysocki
Wysocki

Reputation: 31

Passing CGI command line parameters to a PHP file

A company is sending info to my site and they want to send it to a CGI file as:

mysite.com/cgi-bin/process.cgi?custid=ab123&amount=12345

I have to write the parameter data to a MySql db and I'd rather use PHP (since I don't know cgi). How can I pass the url parameters to my php script? Also, if I redirect to a php file, would the sender know that I was doing that? Can't I just "call" the php file from the cgi script?

Upvotes: 2

Views: 6123

Answers (3)

Cary Millsap
Cary Millsap

Reputation: 832

Using parse_str without a second parameter to store the result of the parse is deprecated in PHP 7.2.0 (http://php.net/manual/en/function.parse-str.php). The function does not return a value now. You can pull the query string from $_SERVER['QUERY_STRING'], so the parse_str call becomes parse_str($_SERVER['QUERY_STRING'], $destination), like this:

<?php
$DEBUG = true;
if ($DEBUG) echo "<p>PHP: good to go</p>";
if ($DEBUG) echo $_SERVER['QUERY_STRING'];
parse_str($_SERVER['QUERY_STRING'], $_GET);
if (empty($_GET)) {
    if ($DEBUG) echo "<p>Not picking up the GET.</p>";
    exit;
}
if ($DEBUG) echo "<p>Got a GET.</p>";
if ($DEBUG) print_r($_GET);
?>

Upvotes: 2

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

To run PHP script as CGI you need to know these

  1. As CGI PHP will not run as a apache handler, rather run as a process.
  2. PHP will not populate $_GET or $_POST,
  3. Your php file should be executable chmod +x
  4. The shebang line should be #!/usr/bin/env php or #!/usr/bin/php
  5. GET data should be read from QUERY_STRING and POST, PUT should be read from STDIN.
  6. HTTP headers should be sent manually.

So your process.cgi will look something like this,

#!/usr/bin/env php-cli
<?php
// populating $_GET
$_GET=parse_str(getenv('QUERY_STRING'));
$custid=$_GET['custid'];
$amount = $_GET['amount'];
// do work

echo "Content-type: text/html\r\n";
echo "Connection: Close\r\n\r\n";
// start output here.
?>

Upvotes: 3

Wireblue
Wireblue

Reputation: 1509

You could write a normal PHP script to process the data they pass (using the $_GET variables), and setup a .htaccess redirect to mask the fact that it's not handled by an actual CGI script.

Just put this in a .htaccess file in the site root, alongside the PHP script (called "process.php" in this example).

RewriteRule ^cgi-bin/process.cgi$ process.php [L]

You could run the PHP script through a CGI script, but it just adds more complexity. Keep it simple.

Upvotes: 1

Related Questions