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.
Related
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
I know that in PHP, once you make a request, browser will go in a waiting mode until PHP does it's operation on the server and send the results back. In the meantime, there is no live connection between the browser and the Server while PHP is doing it's work.
I was wondering if same goes with JSP, or connections are handled differently?
First of all JSP is not a programming language. It's just a technology.
I guess that your question goes more into how they work right (Java and PHP)? So to put you in a simple prespective and with a simple answer, take into consideration that both PHP and Java are scripting languages. The main difference is that Java is compiled, before going to the server, to bytecode and then that bytecode is interpreted by JVM when the request is made. On PHP the code is interpreted (translated to bytecode) on the run and executed by the server. On both cases an answer to you request is given back to browser.
On the middle in between your request and the answer, there's JSP which is a technology that makes it possible for you to write HTML with some dynamic scripting in the middle. Much like a template to something (you can also compare it to a templating engine on PHP like twig). You write it only on your views and it gets compiled by getting parsed to Java Servlets.
I hope my answer makes you investigate a little bit because it has a
I have a PHP script for my contact form, but my host is not compatible with PHP scripts. Is there a way to get this PHP code in an <script>tag?
No, there is not. PHP runs on the server, not on the client.
And this is for good reasons. A lot of the things you do with PHP, you wouldn't want to let the client do anyway. For instance loading data from the database - if you gave the client your database password it could get any data from your database.
Some of the things done with PHP could be done in JavaScript instead, but in quite different ways. But not all things could.
If your host does not support PHP, you will either have to live without it or change host.
If your server is not compatible with PHP how do you plan one running PHP? To answer your question, no.
However you could look into using node.js
check this out http://www.nodemailer.com/
No you can't, because PHP is a server-side language, so if your server doesn't support PHP you can't do anything: tags are for client-side languages, such as Javascript, so in this case are useless.
What languages does your server support?
No. If the PHP software itself isn't installed on the server, it isn't available to you to run from any scripts as it is server-side code and has nothing to do with the browser (client-side).
However, if PHP was installed on the server, you can run PHP code within <script> tags as follows:
<script language="php">
// Your PHP code
</script>
(But that isn't good practice)
It's not a good practice to use server side scripts on the front end, better use client side scripts, say javascript. Server side scripting should be used to serve and consume data, to clean user submitted data mainly.
Please make you a favor and enter javascript . There are many good modern frameworks like ANGULARJS and REACTJS, just to mention my preferred.
Having said that, I answer your question, no it's not possible, but your hosting should support any server, so better ask what server scripting does it provide, because it must. The majority of web hostings provide PHP as default.
I'm considering the idea of a browser-based PHP IDE and am curious about the possibility of emulating the command line through the browser, but I'm not familiar enough with developing tools for the CLI to know if it's something that could be done easily or at all. I'd like to do some more investigation, but so far haven't been able to find very many resources on it.
From a high level, my first instinct is to set up a text input which would feed commands to a PHP script via AJAX and return any output onto the page. I'm just not familiar enough with the CLI to know how to interface with it in that context.
I don't need actual code, though that would be useful too, but I'm looking for more of which functions, classes or APIs I should investigate further. Ideally, I would prefer something baked into PHP (assume PHP 5.3) and not a third-party library. How would you tackle this? Are there any resources or projects I should know about?
Edit: The use case for this would be a localhost or development server, not a public facing site.
Call this function trough a RPC or a direct POST from javascript, which does things in this order:
Write the PHP code to a file (with a random name) in a folder (with a random name), where it will sit alone, execute, and then be deleted at the end of execution.
The current PHP process will not run the code in that file. Instead it has to have exec permissions (safe_mode off). exec('php -c /path/to/security_tight/php.ini') (see php -?)
Catch any ouput and send it back to the browser. You are protected from any weird errors. Instead of exec I recomment popen so you can kill the process and manually control the timeout of waiting for it to finish (in case you kill that process, you can easily send back an error to the browser);
You need lax/normal security (same as the entire IDE backend) for the normal PHP process which runs when called through the browser.
You need strict and paranoid security for the php.ini and php process which runs the temporary script (go ahead and even separate it on another machine which has no network/internet access and has its state reverted to factory every hour just to be sure).
Don't use eval(), it is not suitable for this scenario. An attacker can jump out into your application and use your current permissions and variables state against you.
The basic version would be
you scripts outputs a form with a line input
The form action points to your script
The script takes the input on the form and passes it to eval
pass any output from eval to the browser
output the form again
The problem is, that defined functions and variables are lost between each request.
Would you could to is to add each line that is entered to your session. Lets say
$inputline = $_GET['line'];
$_SESSION['script'] .= $inputline . PHP_EOL;
eval($_SESSION['script'];
by this, on each session a the full PHP script is executed (and of course you will get the full output).
Another option would be to create some kind of daemon (basically an instance of a php -a call) that runs on the server in the background and gets your input from the browser and passes the output.
You could connect this daemon to two FIFO devices (one for the input and one for the output) and communicate via simple fopen.
For each user that is using your script, a new daemon process has to be spawned.
Needless to say, that it is important to secure your script against abuse.
Recently I read about a PHP interpreter written in Javascript php.js, so you could write and execute PHP code using your browser only. I'm not sure if this is what you need in the end but it sounds interesting.
We've tested some products at my university for ssh-accessing our lab servers and used some of the Web-SSH-Tools - they basically do exactly what you want. The Shell-In-A-Box-Project may be bound to any interpreter you like and may be used with an interactive php-interpreter, if desired (on the demo-page, they used a basic-interpreter). The project may serve as a basis for a true PHP-IDE. These have the advantage of being capable of interacting with any console-based editor as well (e.g. vi, emacs or nano), as well as being able to give administrative commands (e.g. creating folders, changing ownerships or ACLs or rebooting a service).
Mozilla also has a full-featured webbased IDE called Bespin, which is also highly extensible and configurable.
As you stated, that the page is not for the public, you of course have to protect the page with Authentication and SSL to combat session hijacking.
I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by mod_php5 and Python through mod_wsgi, usually.
Now I wonder what's the best way to call this PHP ad management code from within my Python code in a most efficient manner (the ad management code has to be called multiple times for each page)?
The solutions I came up with so far, are the following:
Write SOAP interface in PHP for the ad management code and write a SOAP client in Python which then calls the appropriate functions.
The problem I see is, that will slow down the execution of the Python code considerably, since for each page served, multiple SOAP client requests are necessary in the background.
Call the PHP code through os.execvp() or subprocess.Popen() using PHP command line interface.
The problem here is that the PHP code makes use of the Apache environment ($_SERVER vars and other superglobals). I'm not sure if this can be simulated correctly.
Rewrite the ad management code in Python.
This will probably be the last resort. This ad management code just runs and runs, and there is no one remaining who wrote a piece of code for this :) I'd be quite afraid to do this ;)
Any other ideas or hints how this can be done?
Thanks.
How about using AJAX from the browser to load the ads?
For instance (using JQuery):
$(document).ready(function() { $("#apageelement").load("/phpapp/getads.php"); })
This allows you to keep you app almost completely separate from the PHP app.
Best solution is to use server side includes. Most webservers support this.
For example this is how it would be done in nginx:
<!--# include virtual="http://localhost:8080/phpapp/getads.php" -->
Your webserver would then dynamically request from your php backend, and insert it into the response that goes to the client. No javascript necessary, and entirely transparent.
You could also use a borderless <iframe>
I've done this in the past by serving the PHP portions directly via Apache. You could either put them in with your media files, (/site_media/php/) or if you prefer to use something more lightweight for your media server (like lighttpd), you can set up another portion of the site that goes through apache with PHP enabled.
From there, you can either take the ajax route in your templates, or you can load the PHP from your views using urllib(2) or httplib(2). Better yet, wrap the urllib2 call in a templatetag, and call that in your templates.