jeudi 13 août 2009

using a CGI with PHP-CGI

I started to learn a bit more the CGI... :-)
As it is difficult to find some documentation on the web, I will share some findings
I will use PHP-CGI as a show case.

A CGI is a program that will use the environment variables to run. The output is directly sent back to the browser.

there is two cases, the GET and the POST methods,

summary of the environment variables:

SCRIPT_FILENAME -> name of the script (seems to be specific to PHP)
QUERY_STRING -> contains the query string of the url (ie firstname=Sylvain&lastname=Pointeau)
CONTENT_TYPE -> ie application/x-www-form-urlencoded
CONTENT_LENGTH -> length of the posted data on stdin
HTTP_COOKIE -> the cookies

sample for a GET request:

to test it in php on unix
>export SCRIPT_FILENAME=sample.php
>export QUERY_STRING=firstname=Sylvain&lastname=Pointeau
>export CONTENT_TYPE=application/x-www-form-urlencoded

... and for the POST method:

The post variables will be written in stdin for the cgi
we just need to indicate the length of the posted data via the variable

so for instance:
>export SCRIPT_FILENAME=sample.php
>export CONTENT_TYPE=application/x-www-form-urlencoded
>echo "firstname=Sylvain&lastname=Pointeau" | php-cgi

You will may encounter a issue when you will try to execute the samples:
a security issue to run php-cgi from the command line.

there is a line in the php.ini to modify:

; cgi.force_redirect is necessary to provide security running PHP as a CGI under

; most web servers. Left undefined, PHP turns this on by default. You can

; turn it off here AT YOUR OWN RISK

; **You CAN safely turn this off for IIS, in fact, you MUST.**


cgi.force_redirect = 0

Set this variable to 0 to allow the execution of php-cgi from the console ( and not only through apache )

The best would be to have a separate php.ini and tells php to use it:
>php -c myphpfile.ini


Aucun commentaire:

Enregistrer un commentaire