What renders the HTML? - php

In PHP you can write html along with PHP, like:
<html>
<head>
<?php echo "HTML Title from PHP "; ?>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
I would like to know what is this, and how it is working, and in what was written, and how deep do I need to go to understand it?
Nowadays I hear about template engines, but there are lots of template engines for PHP too, so it sounds stupid(for me) to write a template engine on a template engine also as I understood, a template engine parses the whole file just to replace the commands, then it starts to output the file contents too, so it doesn't feels to me that it would be the part of the system, thus loosing performance. ( Maybe I'm totally wrong but seriously this is what I feel when I hear it :P )
EDIT
Guys, when I say what renders HTML I mean what renders HTML in PHP? In a node.js file you can't write any HTML because nothing is processing it.

Trying to avoid too much information, but here is the full cycle of PHP when used with Apache on Linux.
Prerequisities
A common server setup is called the LAMP stack which stands for Linux, Apache, Mysql, and PHP. Generally you can find dozens of ready to use LAMP stack setups along with guides for using them so in context of your question, all you need to focus on is Apache and PHP.
Stage 1 - Delegation
When a web browser contacts a web server running Apache with PHP, the first step is for Apache to find the desired content. Say you go to www.mywebsite.com/hello.php, Apache is going to see you're looking for a file called hello.php. At this point, because of the suffix (.php) , Apache knows that this file needs to be interpreted by PHP so it delegates processing to the PHP interpreter.
Stage 2 - Setup
The hand over from Apache to PHP includes a slew of headers that tells PHP the following: what kind of transaction is being processed ( GET/ POST/ PUT/ DELETE ), the IP address of the incoming request, the browser's user agent ( Firefox, MSIE , IPhone, etc ), if there are cookies. More importantly, Apache hands to PHP the path to hello.php file on the server.
Stage 3 - Processing
Depending on configuration, PHP might need to do some basic house keeping ( setting itself up ) but under ideal conditions its ready to go and opens hello.php Part of PHP is a module called a lexer which looks at hello.php and figures out how to deal with the file. With the example provided a very simple example might look like:
T_STRING = "<html>\n\t<head>\n\t"
T_OPEN_TAG;
T_ECHO;
T_STRING = "HTML Title from PHP ";
;
T_CLOSE_TAG;
T_STRING = "\t</head>\n\t<body>\n\t<h1>hello world!</h1>\n\t</body>\n</html>"
Note, I've made up most of the T_ codes, but they're pretty close to what is real.
Line 1 - PHP knows it's outside of what called scope, so it immediately passes this entire string to Apache, the webserver. Apache will most likely then pass this entire string onto the web browser.
Line 2. - T_OPEN_TAG tells PHP it's entering into the PHP scope and waits it's first instruction.
Line 3 - T_ECHO tells PHP it's going to make an echo statement, so it's rules then kick in to look for an expression or string to output.
Line 4 - As luck would have it, the next token is a string, so PHP now knows it's going to echo "HTML Title from PHP "
Line 5 - The ; tells PHP that the echo statement is complete and more importantly this is syntactically correct... so PHP hands the string "HTML Title from PHP" to Apache which passes this onot the browser.
Line 6 - The Close ?> tag tells PHP that it is leaving the PHP language scope, so it goes back to a much simpler set of rules
Line 7 - Like line 1, the entire string is passed to Apache to be passed to the web browser
At this point, PHP reaches what's called EOF or end of file and knows it's done processing the file hello.php. It does cleanup work and then tells Apache it is done.
Finalization
At this point the request has been mostly fulfilled, Apache will most likely hang up on the web browser, sending notification that all content is complete.
Let me know if you have any questions or need any pointers on where to go next. Also note there is a LOT of details left out of here for brevity/sanity sake, but for just understanding how birds eye view of PHP's relationship to the web browser & web server, this should be enough to get started.
Demonstration script
$test = 'Hello world <' . '?' . 'php echo \'this is in scope\'; ?' . '> and we\'re done';
$tokens = token_get_all($test);
print_r($tokens);
The output will be real world token string PHP generates. Each token can be either a string or a three element tuple/numeric array where index 0 == the Token ID, index 1 == raw string, and I can't for the life of me remember what the third element is. Use token_name if your curious what each token's name is.

First off, PHP IS a template engine, when you use it like in your example.
You really don't need anything more, if you want to keep it simple.

anything inside the <? ?> braces is php code - it's executed on the serverside, and then it outputs the plain HTML to the client, at which point the client's web browser renders it.
Have a look at this diagram.

Your browser is only ever the thing that renders HTML. Whether its written via PHP, javascript or asp, in the end, the thing that works out what the text means (as html is only text) is your browser.

the rendered final product is handled by your web browser. (FF is written in C/C++)
before transmission, apache runs all php scripts thru PHP (preprocessor) written in C
if you use a PHP template engine (eg: Smarty) that is written in PHP itself
if you're really concerned with performance, then switch to another language. PHP template engines are not about conserving CPU cycles, or even speed, instead they boost productivity and maintainability, furthermore they empower front-end developers with the ability to maintain more complex templates without knowing PHP, which increases the value of their work, while free developers to do more serious coding.

Well, you need to understand the history of web development
to give you an "answer" to your question.
In the 199x when Web development started a lot of people uses
Perl. In these days you often have written code like this:
print "<html>";
print " <head>";
print " <title>", get_site_name(), "</title>";
print " </head>";
print "<body>Hello, World!</body>";
print "</html>";
As you can see in this example, in these days you often end
up writing a lot of HTML, and just include some little dynamic stuff.
Like a counter, a clock that shows time, or other little
things. In these days PHP was born to make this process a lot
easier. Instead of writting Code that prints a lot of HTML,
PHP was/is a templateing Engine that allows you to write
HTML and just include your code. In these days you probably
end up writting 90% HTML and 10% of you logic. In these days,
that was oft everything what you needed and it was a lot easier
this way.
But time changed. Today web development got a lot complexer
as in the earlier days. Today you probably write 90% logic and just
10% HTML. Today nearly everything gets
automatically generated, and comes from a database. Because of
the complexion that raised, today you often write your PHP
Application like
<?php
echo "<html>";
echo "<head>";
echo "...";
echo "</html>";
?>
Well as you can see, evolutions goes backwards. And is not
a big difference as in the days before. PHP programs
most ended in starting the php Tag and generating everything
and echo out everything what is needed like in the old days
with Perl.
But, that is still not enoug, you end where you started. Because
today you have a lot more logic to write in your application,
it is a good idea to seperate your application into many peaces.
You seperate your application intp logic and how you should display
your data.
The logic itself get written in PHP, but to display the
data people tend to use other templating engines, that are much
more modern today and fits the needs better.
Yes, it seems a little awkward to have a Templating Engine
that raised to a general purpose language, where Templating
Engine is written in, but that is how it is.
The question how HTML get rendered, well you have a "php" interpreter often directly embedded in Apache (mod_php) that do all the stuff, but for this description there already exists better answers.

Related

PHP include file based on screen size

<?php
include 'components/server.php';
Is it possible to make it include server.php for desktops and server-mobile.php for mobile devices?
While technically possible, it's absolutely not the best way of doing things.
Why?
Because PHP runs on the server and only the output of that PHP execution is given to the browser. You would probably be wanting something using javascript which can load and then seamlessly react to the browser conditions, such as screen size and/or dimensions.
If you're trying to change which PHP script is running based on the browser criteria (as mentioned above) this sounds very much like your programming logistics are simply wrong.
If you somehow really do need to change PHP script execution based on end-client (browser) characteristics you could do this by calling a script based on javascript AJAX or using mechanisms mentioned in comments above, but as said, you're almost certainly "doing it wrong".
Alternative
It would be far better to load everything you need in PHP and then pass all of that content to the browser (as output; HTML, CSS, Javascript, etc.) for the Javascript in the browser to then decide which parts of the data it needs to use and ignoring the others.

cURL PHP - load a fully page

I am currently trying to load an HTML page via cURL. I can retrieve the HTML content, but part is loaded later via scripting (AJAX POST). I can not recover the HTML part (this is a table).
Is it possible to load a page entirely?
Thank you for your answers
No, you cannot do this.
CURL does nothing more than download a file from a URL -- it doesn't care whether it's HTML, Javascript, and image, a spreadsheet, or any other arbitrary data; it just downloads. It doesn't run anything or parse anything or display anything, it just downloads.
You are asking for something more than that. You need to download, parse the result as HTML, then run some Javascript that downloads something else, then run more Javascript that parses that result into more HTML and inserts it into the original HTML.
What you're basically looking for is a full-blown web browser, not CURL.
Since your goal involves "running some Javascript code", it should be fairly clear that it is not acheivable without having a Javascript interpreter available. This means that it is obviously not going to work inside of a PHP program (*). You're going to need to move beyond PHP. You're going to need a browser.
The solution I'd suggest is to use a very specialised browser called PhantomJS. This is actually a full Webkit browser, but without a user interface. It's specifically designed for automated testing of websites and other similar tasks. Your requirement fits it pretty well: write a script to get PhantomJS to open your URL, wait for the table to finish rendering, and grab the finished HTML code.
You'll need to install PhantomJS on your server, and then use a library like this one to control it from your PHP code.
I hope that helps.
(*) yes, I'm aware of the PHP extension that provides a JS interpreter inside of PHP, and it would provide a way to solve the problem, but it's experimental, unfinished, would be still difficult to implement as a solution, and I don't think it's a particularly good idea anyway, so let's not consider it for the purposes of this answer.
No, the only way you can do that is if you make a separate curl request to ajax request and put the two results together afterwards.

How do I constantly update a variable in PHP as a user changes input?

I looked for answers to this question, and it seems that most people have a specific problem. I'm looking for a more general answer. I have a text box where a user will type in their name and I would like to have PHP constantly monitor the text box and change the value of the $name as it is typed or edited.
I would also like to do the same with buttons, and as different buttons are clicked, the content of a variable would change to match that which the button represents. Basically, is there a way to get PHP to constantly run on the page and gather information from a user as it is changed?
It seems like it should be possible, but my experience with PHP is limited, and I'm not sure how to begin, so I don't have any code to really show.
This sounds to me like you require an ajax script checking for input changes(eg/ keystroke, on_blur or on_click for your buttons) and sending back to a php script that will update your variables/tables and return the new variables to the ajax script once they are updated.
1 - Ajax checking for changes on the page, and firing off to a php script on server.
2 - Have a method in your js that waits for the action to be completed and load the new variables into the HTML document.
Basically look up Ajax/PHP - Check username availability, Then adapt to your specific needs.
:)
Simple ajax script will be what your after, there are many scripts available for checking username availability --- As for a lone PHP script, this will not be possible as the PHP code has already ran on the server before the html document is rendered to the browser.
My first answer so my wording may not be perfect comment back if i have confused you more.
It seems like it should be possible, but my experience with PHP is limited, and I'm not sure how to begin, so I don't have any code to really show.
Yes, it's possible, but most likely only due to the nature that the browser (e.g. Firefox) and PHP itself are Free Software.
A proof of concept is missing so far, so you really need to start at a very basic level.
You can download these software packages and modify them to your needs, e.g. make the browser interactively corresponding to the DOM and DOM events process PHP scripts that you embed like script tags inside HTML.
But well, as you wrote, you're starting, so I guess, you don't want to start with rewriting the browser and the PHP interpreter, so even if possible, it's perhaps best to stick that interactive part inside the browser to Javascript and some HTTP request / response programming on the server with PHP.

How I could Render PHP code from MySQL database?

I am creating some kind of custom CMS (home automation).
Well I am not a PHP developer - just hobbyist.
What I am trying to achieve is:
In my index.php page I have something like:
"<?php echo $pageBody; ?> "
PageBody I am fetching from Database, well it works well for HTML, JS. But it doesn't work with PHP code source.
I done some research I believe this is related to PHP security restrictions.
My question: Does anybody would be able to provide safe sample (cannot find any samples like this) - how I should do this.
I am trying to insert some php code and render it eventually via browser:
<div id="outer">
<div id="inner">
***PHP Code should go here***
</div>
</div>
At the minute - it is being rendered as text. However I can render properly HTML and JS.
My preferable way would be - as much as possible secure.
Many Thanks Guys!
When you retrieve PHP code from a database text field, the PHP interpreter does not "know" that it should parse the data as a PHP script. To the PHP interpreter, the data in that field is no different from any other data -- it is all strings without any special significance.
You could use eval (docs) to accomplish this if you're dealing with pure PHP scripts. Be forewarned: eval is considered "evil" because using it comes with risks, especially if your users will have any input as to the content of the database.
In your case, it sounds like you want to parse mixed PHP and HTML that is stored in a database field. In order to do this, you'd need to write the database data into a file, then include it so the PHP interpreter can do its thing. You should implement some kind of caching mechanism in this process, otherwise it might become heavy on your server with many users. You may also want to use output buffering (docs) to capture the output instead of immediately sending it out.
Briefly, you'd want to do something like this:
$content_from_db = "<h1>Hello <?php print 'Clarisse'; ?></h1>";
$identifier_from_db = '12'; // like the primary key from the table
$file_handle = fopen('cached_content/CACHE_'.$identifier_from_db.'.php', 'w');
fwrite($file_handle, $content_from_db);
fclose($file_handle);
// here is where you'd start output buffering, if you're going to do that (optional)
include('cached_content/CACHE_'.$identifier_from_db.'.php');
// and then here you retrieve the output buffer's content (optional)
Please note that this is not a "traditional" way of including dynamic content, and the above code is not production-ready. Without knowing your use case, I can't say for certain, but this idea of storing PHP code in the database is a rather unusual way to proceed.
Another alternative to rolling your own is the smarty template library. Check it out here: http://www.smarty.net. With smarty, you can write a resource plugin to pull the templates from the database. It would look something like the code above (more info)
Documentation
fwrite - http://php.net/manual/en/function.fwrite.php
include - http://php.net/manual/en/function.include.php
PHP basics on theopensourcery.com - http://theopensourcery.com/phpbasics.htm
Server-side scripting on Wikipedia - http://en.wikipedia.org/wiki/Server-side_scripting
eval - http://php.net/manual/en/function.eval.php
Output Control (buffering) - http://php.net/manual/en/book.outcontrol.php
Smarty - http://www.smarty.net
to execute PHP that you store in a string (or database) you can use the eval function, but be careful it could be somewhat dangerous.
You can't render (probably you mean execute) php code in the browser, because php scripts execute on the server and then the output is sent to the browser. By the time the browser recieve the response, script has already finished execution.
You can fetch the code from database and use eval() before sending the output. But you must be aware of drawbacks from this approach.
Browser cannot render (execute) PHP code. PHP is something that the server executes and sends to the browser as plain HTML to display.
For testing purposes you can download and install WAMP thats the most hassle free one stop solution for development.
link : http://www.wampserver.com/en/

Does PHP Include make your code faster?

I have an ad network script like the following
http://cdn.domain.com/ad.php?variables=etc
We have about 10,000 hits a second and we are looking at some improvements for our Pseudo code - this is what I have in mind - my question is - would PHP includes slow down my script like the if else codes and would it be worth minifying the PHP on this page:
<?php
// mysql connect
// get variables from publisher
// if publisher has no ads show advertise here banner
// if resolution from variables is 125x125 show that banner or whatever resolution from the vars
// example www.noadhere.com/image/advertishere_{var}125px.jpg
// if publisher has no ads show advertise here banner and also updated mysql with page views for this publisher
// if publisher has a banner then show it and update mysql with page views
// show also the click code that redirects and updates the record with a hit click
?>
I have updated the code. This is the Phase 1 draft for those who are interested. I think it is so much simpler and I am going to minify this - even though there may not be need - we had 4 mysql actions happening. And now there are 3 - I just made the update views a one liner.
# mysql
$c=mysql_connect("sqlmaster.adserver.com","user","************");
mysql_select_db("adserver", $c);
# vars
$a=mysql_real_escape_string($_GET["z"]);//id
$z=mysql_real_escape_string($_GET["z"]);//zone
$h=mysql_real_escape_string($_GET["h"]);//height
$w=mysql_real_escape_string($_GET["w"]);//width
$d=date("Y-m-d H:i:s");//date
$u=mysql_real_escape_string($_SERVER['HTTP_REFERER']);//url
# constructor
# do we have ads?
$r1=mysql_query("");
if(mysql_affected_rows()==0){
# empty ad code unit
echo 'Blog Empty';
} else {
# we have ads - so show random click code
echo 'Click here .php ? and redirect';
}
# update mysql view table for this ad unit - empty or filled
$r2=mysql_query("");
# end constructor
mysql_close($c);
Any suggestions on improving this would be welcomed. I think the mysql_real_escape is slow.
Using include only slows down your script by the amount of time it takes your server to open the file, which is usually just a fraction of a second. So it wouldn't drastically slow down your script execution.
When using a PHP cache, includes really don't matter that much. However, there definitely is a very minor difference.
My own build scripts automatically replace includes with "normal" code, using a self-made syntax that's backwards compatible with PHP:
/*safeinclude*/ include 'file.php';
My parser then reads the PHP file and notices this include. It grabs the contents of the file.php file and replaces the include with this code (after some cleanup, such as removing the leading <?php tag). It then gets saved to the bin directory, which is where the live files are.
This approach works very well, but you must always check for the <?php and ?> tags. Also, you'd have to split src and bin directories, because you can't change anything that's already live anymore.
Your primary focus area for optimizations should probably be the database though, and other CPU-intensive operations such as loops.
There are lots of ways of making code run faster. Usually splitting code into separate files will not improve performance (selectively including just the code you need instead of a huge library will probably help).
You may have noticed that there aren't a lot of off-the shelf solutions for minifying PHP code - there's a good reason for that. It won't make a lot of difference to the execution time (it does for javascript mainly due to the reduction in network transfer time - not in the reduction in parsing time). PHP code doesn't go across the network. And if you want to reduce parsing time, then using an opcode cache is a much effective solution.
Since this is presumably a significant revenue stream, then you should have the skills to know this already. However a lot of performance improvements come about by trial and error (and careful experiment design and measurement) - you might want to invest some time in developing these facilities.
The good thing about running if and else's is that only the code that is needed to be ran will run. Included pages are loaded in a split of a second and do not really make any difference on the speed. Most big websites have long trails of included files and you don't really notice it.

Categories