PHP Response directly from C / C++ language - php

I am looking for an efficient way of responding to an http request. When a http request is received (apache/php webserver environment), I want to know if I can obtain a reference to php's response instance inside a c++ library method and write the output data directly to the response instance within C++ context.

Normally, you'd simply redirect the request to your external C/C++ program through mod_fastcgi, processs it completely in your program and write the repsponse to the client.
If not possible, you could include the program output into the generated web page by accessing your program from Apache as a server side include (SSI).
From PHP, you can also perform a system call to the external program and process the returned output as shown in the link.
Some simple C examples are provided in the fastcgi documentation.
To write a PHP extension in C/C++ (here and there) and make that work in Apache (through mod_php) is possible, but is considered rocket science and therefore discouraged ;-)

Related

How does PHP set HTTP headers with the header() function?

I am learning HTTP and web programming and I was surprised to find out that you can set HTTP headers using php. I thought PHP was used to generate dynamic HTML web pages and create applications. It seems strange to me that PHP can set headers that are sent by the web server (e.g. Apache). I know PHP interpreter reads the PHP file and generates an output usually in the form of HTML.
Does this process work with pipes? In my opinion the apache server has to be able to receive commands from the PHP interpreter or it has to be able to interpret PHP functions itself. They are separate processes I think.
What mechanism is used by PHP to set headers to the web server application (httpd or Apache or something else)
Do all web servers support receiving and setting headers that are received via PHP?
Is it possible to set HTTP headers with all backend languages?
I searched through the website and I did not find an aswer to my question.
More specifically I want to know what command can apache or other web server send to PHP.exe application or PHP-CGI.exe application to receive other information besides the outputted HTML file.
Indeed an interesting question. Using command-line tools, I can only access the produced HTML output. Hence php -r"header('Location: http://someurl.com');" will produce nothing from command line.
When I would look at my setup with IIS (not Apache) though, I see that IIS is using PHP-CGI.exe to communicate with PHP. Looking at the optional arguments of PHP-CGI.exe, I see -b can be used to set a Bind Path for external FASTCGI Server mode. I guess in this server mode there will be room to communicate header information separate from produced HTML.
I don't know the exact details of the FASTCGI protocols to go more indepth. But I guess this is what you wanted to know.
EDIT:
When googling about this, I came upon this thread:
How does PHP interface with Apache?
Sending headers from PHP is very useful, for example, you can send headers that force the browser to download a file vs. displaying it on screen (for file scripts, reports that output CSV), controlling cache headers and performing page redirection.
As stated in one of the comments, PHP being a module of Apache in many installs, it sends headers directly through that. Otherwise, the headers would be sent via CGI / FastCGI, or PHP-FPM for nginx.
What you're thinking of more or less is of a templating engine, which PHP performs well at, but PHP has other functions that would normally not be seen in a template engine, such as opening sockets, handling files, and so on.
Any backend language I've had experience with has support for sending HTTP headers, and I would consider any web-oriented back-end language incomplete without this ability.
header('Location: http://www.google.com/');
In this way we can set header in php

How to integrate C++ application into PHP website?

I have a c++ application that processes a sentence and responds back to the respective user. I have a website using php that I would like to post data to this application and receive this response. Ideally, the C++ would run on the webserver and not have to be fully loaded each time it is used, but i haven't been able to get a simple 'hello world' (with cgi or c++) to work on the webserver.
What would be the easiest way to integrate a c++ application into a website? Should this work with any webhost?
To Integrate them you can take two approaches.
1) Integrate C++ as a function into PHP with http://www.php-cpp.com
You can create a function, say my_complex_function, that when called in PHP, will execute a C++ code. You can read the site's documentation for information about it.
2) Keep them separate and communicate through HTTP/Pipes/Sockets/Other
You could build a C++ daemon that opens up some kind of communication interface like a Socket, then with PHP you open a socket to it, send the information through the socket, and receive the answer there too.
You can find socket examples for PHP here: http://php.net/manual/en/sockets.examples.php

PHP Execute Code AFTER user receives a response

I have a api built with PHP & Codeigniter + RestClient and its getting to the point speed matters. We have ALOT of code that the user should really not need to have to wait on to receive a response from the API that I would prefer to be executed AFTER the user receives a api response. Is this possible and if so how?
This is possible if your server run PHP as PHP-FPM. See in documentation functions with prefix fastcgi_
You can move your "special" code to separate file and run this file as daemon. Not sure about PHP scripts, but for Python scripts this is possible.

How does a webserver interface with PHP

I want to handle http requests via another webserver or own written server in future.
I want to understand how to provide php with request data properly.
in what form request data should be provided
how data is provided to php, via stdin or somehow else
how php handles received request data afterwards, any additional actions required to fill $_SERVER variables etc.
It's pretty simple actually. The Webserver communicates with PHP through the CGI interface. This entails setting up environment variables, invoking the php interpreter, piping a POST body through stdin, and then reading the PHP response from stdout.
Call PHP from virtual/custom "web server"
How to pass POST data to the PHP-CGI?
http://pear.php.net/package/HTTP_Server
What is Common Gateway Interface (CGI)?
As to PHP postprocessing the $_SERVER variables: That's fairly minimal, it only constructs PHP_SELF and PHP_AUTH_USER etc. as documented in the manual. The rest is provided by the webserver (e.g. all HTTP headers converted into HTTP_* env variables).
Go download the source code for php, and look at the code for mod_php, written in C I believe, cause that's where it's done.

Why PHP script is not workig in a web browser?

We have all seen many question on StackOverflow that are founded upon the idea that PHP works like Javascript. Where the person clearly does not understand that PHP is a Preproccessor and only works before the page is sent out.
A clear example of this is in the following code, where runCommand() will not run when the user presses the button.
Click Me!
as it would in Javascript
Click Me!
I've seen many questions like this that are from new people that just simply don't realize 'how' PHP works.
My question is: Where is a great resource that explains how PHP works?.
I want to be able to redirect people to a page that can get them going on the correct track and know what being a Preproccessor means.
(This also allows me to be lazy and not have to write an explanation every time it comes up, but don't tell anyone!)
If you don't know of a place that describes this well, feel free to provide your own interpretation.
As Carl Smotricz points out, there is a part of PHP that can be used outside of the browser. But I'm mainly talking about in a Apache enviorment where a user requests a web page, and expects to get something back, usually in HTML.
Wikipedia is always a great resource of information. I suggest:
Server-side scripting
vs
Client-side scripting
And Wikipedia also has pictures:
It could be that you're the one who does not understand how PHP works. PHP is a full language interpreter, and it's completely possible to run PHP scripts without a browser, outside of a Web server: On the command line or in an IDE or other GUI environment.
The PHP preprocessor of which you speak is only the function of an Apache module that calls on the PHP interpreter for this particular limited purpose.
The PHP code is interpreted on the server side an only the output of your PHP code will be send to the client.
So if a PHP file is requested, the web server sends the PHP code to the PHP interpreter, waits for the output and then sends the output back to the client.
In short, PHP belongs to the server, it usually then outputs HTML but it's not here for that (or at least, not only for that).
The user browser "sees" only what remains after php did its thing.
Javascript belongs to the client (aka browser): it usually handles the DOM created by parsing the HTML, which is (possibly) produced by executing PHP. Javascript can behave differently in different browsers (everyone who has written JS scripts know about cross-browser problems, do you remember IE6?)
Javascript can't handle database all by itself; It has to rely on a sever-side language (php, maybe? ;) (except if talking about node.js)
BTW, AJAX can be a good reference to understand what exactly PHP does and what JS does.
An important distinction is that JavaScript in a browser is event driven. That is why a click handler is not executed right away as the page loads, for example. The javascript could not be waiting to respond to that click either, if it was not for the event-driven style of dom programming.
I don't really think this is what is meant by the term 'preprocessor'. the client/server side distinction is more important. For instance, have you heard of any other server side language being referred to as a preprocessor when performing the same tasks as PHP?
php responds to http requests in the typical server-side scenario. the browser reads this response and is responsible for rendering it and running any additional dynamic scripts embedded in the response on the client side. that is essentially the division of labor in that scenario.
PHP is server-side scripting language which means all php code is executed before page is sent to the client side. For that reason you will never see
<?php ... ?>
in page source.
On high abstraction level...
You can consider web server (hardware) as component of four different parts. Webserver(software, for example Apache), File system, database and PHP plugin.
So for example when you sent page request (for some page .../example.php) to the web server Apache will try to find that page in file system and if the page exists he will call php plugin to executes all
<?php ... ?>
code (of course including db queries). After that page is sent back to the client side where you can manipulate with page through JavaScript, designed it through CSS...
More on: https://www.youtube.com/watch?v=PemsuAfc7Jw
The reason why PHP scripts are not working in a web browser is only because web browsers do not support PHP (at least I don't know any). This fact is not as trivial as one may think.
And it may sound disturbing, so take a look at HTML specifications on W3C website of HTML 5 and HTML 4.01 (because it has more verbose examples). What you can find? That scripts can be written in languages other than JavaScript!
Here is an example from HTML 4.01 documentation (section titled Specifying the scripting language).
(...)
Here's a more interesting window handler:
<SCRIPT type="text/javascript">
function my_onload() {
. . .
}
var win = window.open("some/other/URI")
if (win) win.onload = my_onload
</SCRIPT>
In Tcl this looks like:
<SCRIPT type="text/tcl">
proc my_onload {} {
. . .
}
set win [window open "some/other/URI"]
if {$win != ""} {
$win onload my_onload
}
</SCRIPT>
Script written in Tcl is perfectly O.K. in HTML! What about PHP? HTML5 documentation says:
A user agent is said to support the scripting language if each
component of the script block's type is an ASCII case-insensitive
match for the corresponding component in the MIME type string of a
scripting language that the user agent implements.
(...) User agents may support other MIME types for other languages,
but must not support other MIME types for the languages in the list
above. User agents are not required to support the languages listed
above.
Thus it is only up to web browser (user agent) if it is going to support PHP or not. Playing with W3C example, PHP aware web browser might have accepted something like this.
<script type="text/php">
function my_onload() {
. . .
}
$win = $window->open('some/other/URI');
if ($win !== false)
$win->onload = 'my_onload';
</script>
So, the reason why people ask such questions is not that they don't know how PHP works. It is because they don't understand web technology in general. They fail at point, which requires understanding of what, where and why is supposed to be executed.
The PHP compiler executes in the server as a CGI script. A CGI script reads from Standard Input and writes to Standard Output, similar to a console or command prompt program. The PHP compiler reads the file containing HTML and embedded PHP and writes the HTML out and (when encountered) executes the PHP and writes the result of the PHP code. The output is received by the server then sent to the client.
See PHP: CGI and command line setups - Manual that says:
By default, PHP is built as both a CLI and CGI program, which can be used for CGI processing.
The difference between CLI and CGI are insignificant here.
Also see PHP: What is PHP? - Manual that says:
the code is executed on the server, generating HTML which is then sent to the client.
See RFC 3875 - The Common Gateway Interface (CGI) Version 1.1. It is the official definition of CGI. PHP seldom uses the original CGI protocol; other protocols such as FastCGI are used and perform the same function as the original CGI protocol but are designed to be more efficient. For the purpose of understanding how PHP works the original CGI protocol is relevant. The following is an excerpt of the RFC.
Abstract
The Common Gateway Interface (CGI) is a simple interface for running
external programs, software or gateways under an information server
in a platform-independent manner. Currently, the supported information
servers are HTTP servers.

Categories