Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing PHP in webserver "environment" without Apache (or other webserver)

Tags:

php

cgi

Is it possible to execute PHP code from a program that does not interface with the script through a webserver? Initially, I thought of the CLI PHP interpreter, but that doesn't contain any of the $_SERVER or $_REQUEST varaibles common to website requests.

So, if it's possible to emulate, how could the be accumplised? I am not thinking in any specific programming language as i'm sure there is some common interface between webservers and php which would be platform independent.

The aim of this question is to build a Node.JS application that can opperate as a webserver, then (when needed) can execute PHP scripts (with specific inputs), fetch the response, then if needed some additional processing on the output, then write it to the client.

like image 771
topherg Avatar asked Oct 22 '22 19:10

topherg


1 Answers

Unless you want to build a PHP module for Node.JS, I think CLI is your only choice - you could pass the required variables through the command line, and I guess nothing speaks against rebuilding them inside the script:

php -f myscript.php /websites/myscript domain.com 1.2.3.4.5

Now, the ideal way would be to take these arguments and write them into variables that you then use in your script.

If you have an existing script that utilizes $_SERVER, and don't want to go through rewriting it, this would be a working yet inelegant workaround. (Inelegant because you're not normally supposed to write into $_SERVER, $_GET and the like.)

$_SERVER["REQUEST_URI"] = $argv[1];
$_SERVER["SERVER_NAME"] = $argv[2];
$_SERVER["REMOTE_ADDR"] = $argv[3];

CLI: Command line usage

(I'm not quite sure whether overwriting server variables like this is kosher, it feels a bit wrong. But it definitely works in a standard setup. I'll ask the guys in PHP chat what they think... edit: nobody really likes it, but there don't seem to be any major downsides)

like image 173
Pekka Avatar answered Oct 24 '22 14:10

Pekka