Does all HTML get stored in the output buffer? - php

Consider the following PHP file:
index.php
<!DOCTYPE html>
<head>
<title>Welcome to my home page!</title>
</head>
<body>
<?php
for($i = 0; $i < 2000; ++$i)
{
echo $i.'<br>';
}
?>
</body>
</html>
Is PHP loading into memory only the contents of the echo or the static HTML as well?
Maybe the answer is widely known but I have not found any documentation.
I would love an RTM link btw.

The answer is quite simple, to process/find those <? tags the php interpreter needs to read the whole file.
So yes php loads the whole file.
The ob (output buffer) functionality of PHP actually allows you to take advantage of this.
See the first example of the on_start() documentation illustrates this
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
http://php.net/manual/en/function.ob-start.php

PHP's output buffer contains everything.
See: http://php.net/manual/en/language.basic-syntax.phpmode.php
This works as expected, because when the PHP interpreter hits the ?>
closing tags, it simply starts outputting whatever it finds (except
for an immediately following newline - see instruction separation)
until it hits another opening tag unless in the middle of a
conditional statement in which case the interpreter will determine the
outcome of the conditional before making a decision of what to skip
over. See the next example.
So anything outside of a PHP tag is essentially treated as an echo.

Related

Escaping <?php ?> in the JavaScript of a php file

I have a php file, index.php, that contains the jQuery/JavaScript code below. The code is defining a string that will be a new PHP file after it gets ajaxed up to the server. index.php loads fine until I put the PHP line in the first array member. Then when I load index.php I get:
SyntaxError: <html xmlns="http://www.w3.org/1999/xhtml"><head>
Since index.php is a PHP file that is running I know I have to escape the leading < in <?php or the PHP processor will jump in at the server. But apparently I need to do more than that. Does anyone see how I can structure this so that index.php loads and then this code passes <?php ?> up as a harmless string?
$(function() {
var seg1 = ["\<?php phpinfo(); ?>\n",
"<!doctype html>\n ",
"<!-- HTML5 -->\n",
"<html>\n",
"<head>\n",
"<meta charset='utf-8' />\n",
"<title>MyPlace</title>\n" ,
"<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'><\/script>\n",
"<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js'><\/script>\n"
].join('');
}
phpinfo() generates a HTML page by itself, so concatenating that with another document isn't exactly kosher.
That said, you could use output buffering first to capture the output of phpinfo() and then use json_encode() to properly escape it:
<?php
ob_start();
phpinfo();
$info = ob_get_clean();
?>
$(function() {
var seg1 = [<?php echo json_encode($info); ?>,
"<!DOCTYPE html>\n" // etc etc
].join('');
Update
I misunderstood your question; it seems that you allow the upload and execution of arbitrary PHP code on your server. This is highly dangerous and my first advice would be to basically abandon that idea.
If you still feel like shooting your foot off, here's how:
var seg1 = ["<" + "?php phpinfo(); ?" + ">\n",
"<!DOCTYPE html>\n" // etc etc
].join('');

Conditional embed HTML between PHP code blocks?

I'm fairly new to PHP. I started learning it like 3 weeks ago. I cannot find the answer to this question on StackOverflow, Google or Youtube. The PHP documentation to this just confuses me. To get on with the question, how does PHP code mixed in with HTML work?
<?php if (something) { ?>
<p>Hello</p>
<?php } ?>
The p element will only display if something has a truthy value, how is this?... I thought for sure that the PHP engine ignored what was going on around the outside of the codeblocks (e.g. <?php ?>) and only parsed what happens on the inside.
The code below gets parsed by the PHP engine normally and sent to the browser without affecting any HTML elements (even though its clearly between 2 code blocks).
<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>
I hope I'm not going to get flamed for asking this question since a lot of people seem to understand how it works in like a tenth of second.
P.S. I asked this question in chat early and thought I understood it correctly but when I went to implement it my mind was still like, how does this work exactly? It just seems like some kind of hack to me.
Easy now. Definitely need a php tutorial for you to start on http://www.tizag.com/phpT/
Here is what your doing:
<?php
//Anything inside me php processes
if($something)
{
echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>
Quick Note: It is good practice to separate your PHP from your HTML
<?php if ($something) { ?> <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.
In your first example it is indeed true that <p>Hello</p> will be rendered if and only if 'something' returns true.
If you close a php tag with ?> but have an 'unclosed' execution, like if (blah) { ..., the PHP engine understands your desires and does accordingly.
Why?
The PHP engine is kept 'waiting' until the execution is closed with } and then the final result is evaluated and the browser continues on with the lines below.
Obviously if you leave out the final } you will see some errors, which tells you that PHP was expecting you to finish what you started and you did not
Both the php and html are parsed in-line. So, as it moves down your script it will run php scripts within tags, and display html in the order which they are placed. For example:
<? $someVar = "someVar string value"; ?>
<h1>This is a title</h1>
<? if(1 == 1){?>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<? } ?>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: <?=$someVar;?></p> // <?= is a short hand for echo
This will show as:
<h1>This is a title</h1>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: someVar string value</p>
Basically just think of it as the server reading down your script and parsing whatever it sees as it goes. If there is html, it will display it and if there is php which does some sort of calculation and then spits out html, it will show the spat out html.
You can write php code anywhere in HTML using php code block
<?php echo "whatever " ?>
or
<?php echo "<h1>Here everything will displayed in h1 </h1> "; ?>
and if you use control structure ( if, switch etc.. ) then it will behave like all other languages, means if something is true then it will execute the part written between { }.
so if you write an undefined variable in if condition then it will not execute code block of because undefined variable is treated as false condition .
additionaly you can check any variable value by var_dump($variable)
PHP's Alternative syntax for control structures
<!DOCTYPE html>
...
<div>
<?php if ( the_thing === true ) : ?>
<p>The thing is true! \o/</p>
<?php else if ( the_other_thing === true ) : ?>
<p>The other thing is true! meh</p>
<?php else : ?>
<p>Nothing is true :-(</p>
<?php endif; ?>
</div>
...

Can I configure PHP to automatically format the HTML it generates?

For example…
This PHP code
<?php
echo '<html>';
echo '<body>';
echo '<h1>Header One</h1>';
echo '<p>Hello World!</p>';
echo '</body>';
echo '</html>';
?>
Generates this HTML markup
<html><body><h1>Header One</h1><p>Hello World!</p></body></html>
Are there any functions, libraries or configuration options to make PHP automatically apply some simple formatting (line breaks & indentation) based on the nesting of html tags generated in the output? So that instead something like this would be generated…
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>
You could try templating engines like Smarty, Savant, PHP Sugar or VLib.
Or you could go commando with output handling (which I think is a hack). ob_start('ob_tidyhandler');
For the output handling, Tidy might not be installed or enabled, typically the package you will need to install is named php-tidy and you will need to uncomment extension=tidy in your php.ini
You can put html in your PHP script without having to echo it. You also might want to look for a PHP template engine like smarty, so you can separate the view from logic.
I prefer to use heredoc strings and format/indent the HTML myself. Mixing HTML strings inside PHP code quickly leads to unreadable, unmaintainable code. Some advantages of this method:
Quotes don't need to be escaped.
You can put variables inside the heredoc strings.
Even when working with code that loops, you can output the HTML inside heredoc strings. If these strings are indented properly relative to your other blocks of HTML, you will still get HTML code that has good indentation.
It forces you to think about when you want to print HTML, and to print it in blocks instead of lots of little pieces sprinkled throughout your code (very hard to read and maintain).
It's better to separate the PHP code from the HTML as much as you can, whether this means using a templating engine or just putting all of the code before all of the HTML. However, there are still times when it's easiest to mix PHP and HTML.
Here's an example:
<?php
$text = 'Hello World!';
echo <<<HTML
<html>
<body>
<h1>Header One, with some '"quotes"'</h1>
<p>$text</p>
</body>
</html>
HTML;
?>
If I understand your question right, you want to pretty-print the HTML output.
This can be done by post-processing the output of your PHP script. Either by using PHP's output handling feature combined with the tidy extension­Docs:
ob_start('ob_tidyhandler');
Tidy is an extension specialized on cleaning up HTML code, changing indentation etc.. But it's not the only way.
Another alternative is to delegate the post-processing task to the webserver, e.g. output filters in Apache HTTP Server­Docs.
You could do this (my preference):
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
<?php echo '<p>Hello Hello!</p>'; ?>
</body>
</html>
Or:
<?php
$html = '<html><body><h1>Header One</h1><p>Hello World!</p></body></html>';
$tidy = new tidy();
$tidy->parseString($html, array('indent'=> true,'output-xhtml'=> true), 'utf8');
$tidy->cleanRepair();
echo $tidy;
?>";
...would print:
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>
...Or you can use the "<<<" operator where you can set formation by yourself:
<?php
echo <<<DATA
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>
DATA;
If the below code looks useful to generate html with php, try this library
https://github.com/raftalks/Form
Html::make('div', function($html))
{
$html->table(function($table)
{
$table->thead(function($table)
{
$table->tr(function($tr)
{
$tr->th('item');
$tr->th('category');
});
});
$table->tr(function($tr)
{
$tr->td()->ng_bind('item.name','ng-bind');
$tr->td()->ng_bind('item.category','ng-bind');
$tr->setNgRepeat('item in list','ng-repeat'); //using second parameter to force the attribute name.
});
$table->setClass('table');
});
$html->setClass('tableContainer');
});

Can PHP write html command to another file?

I have one question to ask you.
I have 2 PHP files first one is index.php and another one is body.php
index.php contain HTML template like
<html>
<head>
<title></title>
</head>
<body>
<? include('body.php') ?>
</body>
</html>
and body.php query data from database(such as name, nickname, age).
I need body.php to change tag or add more tag in index.php
How should i do in PHP command?
thanks
In your example, body.php can have any HTML output you need. The output of body.php will be included in your final output.
If you need to make the final output of index.php dependent on the body.php file, (for example to insert a title) you can load your content into variables, which can be outputted later.
<?
include ('body.php');
/* $title and $bodyHTML are set in the include file */
?>
<html>
<head>
<title><? echo $title; ?></title>
</head>
<body>
<? echo $bodyHTML;?>
</body>
</html>
You can use fopen() and fwrite() to modify the content of index.php from body.php (assuming that you have the write permissions, of course).
If you mean change the content while the user is viewing index.php and then change index.php, then that isn't possible without telling the user to "click here and view the new code!" (since at that point, you can no longer use headers to refresh the page).
PHP is not a dynamic content language like, for example, JavaScript.
You can't alter variables in part of the page that has already been output. You can use output buffering to capture the output to that point and then do string substitutions on it
<?php ob_start(); // start buffering output
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
include('body.php');
// Get the contents of the buffer and then clear the buffer
$buffer = ob_get_clean();
// Replace your keyword with a variable loaded from body.php
$buffer = str_replace('%nickname%', $nickname, $buffer);
// output the altered head
echo $buffer;
// Stop buffering and output what we just echoed
ob_end_flush();
?>
</body>
</html>
There are a number of PHP template and theming engines out there that make
doing this kind of thing easier. Smarty is a fairly
popular one. Another one I like is Savant but I'm personally partial to the one I created called Enrober.
write db related stuff in body.php file and call those functions from index.php.
Loop those results and built through related tags and display.
Thats it.........
You could output the entire thing from a php object called domdocument, which allows dynamic creation of html documents.
That way, you could change the tags and their content as dynamically as you want.

HTML into PHP Variable (HTML outside PHP code)

I am new to php and wondering if I can have something like this:
<?php
...
magicFunctionStart();
?>
<html>
<head>...</head>
<body>...</body>
</html>
<?php
$variable = magicFunctionEnd();
...
?>
What I have to use right now is
<?php
...
$variable = "<html><head>...</head><body>...</body></html>"
?>
Which is annoying and not readable.
Have you tried "output buffering"?
<?php
...
ob_start();
?>
<html>
<head>...</head>
<body>...<?php echo $another_variable ?></body>
</html>
<?php
$variable = ob_get_clean();
...
?>
I think you want heredoc syntax.
For example:
$var = <<<HTML
<html>
<head>
random crap here
</html>
HTML;
I'm not really sure about what you are trying to accomplish, but I think something like the heredoc syntax might be useful for you:
<?
$variable = <<< MYSTRING
<html>
<head>...</head>
<body>...</body>
</html>
MYSTRING;
However if you are trying to make HTML templates I would highly recommend you to get a real templating engine, like Smarty, Dwoo or Savant.
Ok what you want to do is possible in a fashion.
You cannot simply assign a block of HTML to a php variable or do so with a function. However there is a number of ways to get the result you wish.
Investigate the use of a templating engine (I suggest you do this as it is worth while anyway). I use smarty, but there are many others
The second is to use an output buffer.
One of the problems you have is that any HTML you have in your page is immediately sent to the client which means it cant be used as a variable in php. However if you use the functions
ob_start and ob_end_fush you can achive what you want.
eg
<?php
somesetupcode();
ob_start(); ?>
<html>
<body>
html text
</body>
</html>
<?php
//This will assign everything that has been output since call to ob_start to your variable.
$myHTML = ob_get_contents() ;
ob_end_flush();
?>
Hope this helps you can read up on output buffers in php docs.
I always recommend to AVOID buffer functions (like ob_start ,or etc) whenever you have an alternative (because sometimes they might conflict with parts in same system).
I use:
function Show_My_Html()
{ ?>
<html>
<head></head>
<body>
...
</body>
</html>
<?php
}
...
//then you can output anywhere
Show_My_Html();
$html_content = '
<p class="yourcssclass">Your HTML Code inside apostraphes</p>
';
echo $html_content;
Its REALLY CRAZY but be aware that if you do it :
<?php echo ""; ?>
You will get it:
<html><head></head><body></body></html>
Keep calm, its only php trying turn you crazy.

Categories