Skip to content
Advertisement

Does PHP only work with Apache, or can I make it work with my own c ++ server?

Does PHP only work with Apache, or can I make it work with my own c ++ server?

For example, can I send a request from my c ++ program to php, so that php runs “file.php” and then returns the result to my c ++ program?

Advertisement

Answer

PHP is an interpreted language. Besides using it through Apache mod_php, it supports CGI and FastCGI calls setup. So you can either:

  1. call it’s interpreter in CGI mode to execute a PHP script file; or
  2. run php-fpm server in the background then call it to run any PHP file with the FastCGI protocol.

I believe multiple libraries in C++ are there for making either or both CGI and FastCGI calls. For example, darrengarvey/cgi can do both.

CGI Without a Library

If you go for the CGI path, you can even do it without a library. With php-cgi properly installed, you can make a regular CGI call like this:

echo "test=1" | 
REQUEST_METHOD=POST 
CONTENT_TYPE=application/x-www-form-urlencoded 
CONTENT_LENGTH=6 
GATEWAY_INTERFACE=CGI/1.1 
SCRIPT_FILENAME=/full/path/to/file.php 
REDIRECT_STATUS=true 
REQUEST_URI=/hello/world 
php-cgi

As you can see, a CGI call is a regular system call with some predefined environment variables (a.k.a. Request Meta-Variables). The HTTP request body is supplied to STDIN. The complete HTTP response (headers included) will be sent through STDOUT.

Difference between CGI and FastCGI

Since every CGI call will be a system call, it take time to load PHP libraries / modules into memory everytime you call. FastCGI specified a way to send/receive STDIN, STDOUT, STDERR over line protocol. php-fpm would load up memory and pool connections to make the call faster. Hence the name FastCGI.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement