Search code examples
phpnode.jsexpressfastcgi

Running PHP from nodejs instance


I would like to run php with nodejs like with https://www.npmjs.com/package/node-php

It was nice but I guess it's working only with old version of express and this repo doesn't look to be maintained anymore.

looked like

var php = require('php');
var app = express();
app.use("/", php.cgi("/path/to/wordpress")); 
app.listen(3000);

and then every request made to / ending with .php would call the cgi script that run php and return the result.

Now what I am trying to achieve, looks more like :

  1. from node define which php file to call
  2. pass arguments to it so the php code have the context (payload, arguments, header...)
  3. read back the php code response (preferably in json format)

Is there anyway to do that using the nodejs or do I need to to a web call like proposed for Call PHP methods from NodeJS ?

not having to start a php webserver would be preferable would require more setup and my project wouldn't "work out of the box", I prefer just to install php5 and it's done (I guess it safe memory / proccess as well as these call should be use very often)


Solution

  • You can pass the input through via stdin and then read it with fopen("php://stdin") like a regular file (file_get_contents("php://input") works too). This assumes that you just want to run a simple PHP script, not something that expects all aspects of an HTTP request.

    The output is dependent on your code, so just make sure to call json_encode() when returning.

    Here is the documentation for how to pass the data as stdin in the first place.