I have a php that makes some maintenance operations in my web and I need that the last operation it'll do is to save into a file the content of the screen. I mean, self content.
If the screen shows: "OP1 - OK ..." it has to save into a file this: "OP1 - OK ...".
Saving all the results of my operations into a variable will very hard for me. That's why I need to get the content of the self screen.
Is there any way to do this?
I think you can use an output buffer.
The following is from ob_start's php manual page:
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Related
What is output buffering and why is one using it in PHP?
Output Buffering for Web Developers, a Beginner’s Guide:
Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.
Advantages of output buffering for Web developers
Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.
Output buffering is used by PHP to improve performance and to perform a few tricks.
You can have PHP store all output into a buffer and output all of it at once improving network performance.
You can access the buffer content without sending it back to browser in certain situations.
Consider this example:
<?php
ob_start( );
phpinfo( );
$output = ob_get_clean( );
?>
The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.
You can use output buffering in situations when you want to modify headers after sending content.
Consider this example:
<?php
ob_start( );
echo "Hello World";
if ( $some_error )
{
header( "Location: error.php" );
exit( 0 );
}
?>
I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.
If output buffering is turned off, then echo will send data immediately to the Browser.
If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.
phpinfo
To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.
In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.
php.ini
It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php
Example: ob_get_clean()
Below you can see how to capture an echo and manipulate it before sending it to the browser.
// Turn on output buffering
ob_start();
echo 'Hello World'; // save to output buffer
$output = ob_get_clean(); // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output
echo $output; // send to output stream / Browser
// OUTPUT:
HELLO WORLD
Examples: Hackingwithphp.com
More info about Output buffer with examples can be found here:
http://www.hackingwithphp.com/13/0/0/output-buffering
The Output Control functions allow you
to control when output is sent from
the script. This can be useful in
several different situations,
especially if you need to send headers
to the browser after your script has
began outputting data. The Output
Control functions do not affect
headers sent using header() or
setcookie(), only functions such as
echo() and data between blocks of PHP
code.
http://php.net/manual/en/book.outcontrol.php
More Resources:
Output Buffering With PHP
As name suggest here memory buffer used to manage how the output of script appears.
Here is one very good tutorial for the topic
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Buffers can be nested, so while one buffer is active, another ob_start() activates a new buffer. So ob_end_flush() and ob_flush() are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.
Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php
UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.
Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.
so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.
Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.
Cheers.
You can make fast river
or
You can make safely tama :)
This is a summary of output buffering in php. (XAMPP php.ini )
Output buffering is a mechanism for controlling how much output data
(excluding headers and cookies) PHP should keep internally before pushing that
data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify. Turning on this setting and managing its maximum buffer size can yield some interesting side-effects depending on your application and web server. You may be able to send headers and cookies after you've already sent output through print or echo. You also may see performance benefits if your server is emitting less packets due to buffered output versus PHP streaming the output
as it gets it. On production servers, 4096 bytes is a good setting for performance
reasons.
Note: Output buffering can also be controlled via Output Buffering Control
functions.
Possible Values:
On = Enabled and buffer is unlimited. (Use with caution)
Off = Disabled
Integer = Enables the buffer and sets its maximum size in bytes.
Note: This directive is hardcoded to Off for the CLI SAPI
Default Value: Off
Development Value: 4096
Production Value: 4096
http://php.net/output-buffering
output_buffering=4096
When we say that a function's result is sent to output buffer, it means that the result is not visible until echoed. And for functions that output directly, we use ob_start to direct the result to the output buffer (before it hits the browser as plain html) so that we may manipulate it, and then if desired, echo it.
The result of the function readfile() is directly visible, which is the contents of a certain text file, for example. then my question is:
Why it is mentioned in php documentation that readfile() sends the contents to the output buffer ?! (while in fact it is displayed directly).
Am I missing something?
When we say that a function's result is sent to output buffer, it means that the result is not visible until echoed. No it doesn't mean that!
Because it is sent to the output buffer, which (unless you've explicitly executed an ob_start() to buffer the output before sending it to the browser) is sent directly to the browser (or whatever).
All output is sent to the output buffer, but unless you've set the buffer to hold output before sending it, it gets sent.
EDIT
Of course, a webserver may be configured to cache output until a certain volume of data has been sent, but that isn't the same as PHP output buffering
Well, when the readfile() is executed, the output goes directly to stdout.
it is useful to know this behavior when php is used as a bash script:
#!/usr/bin/php
<?php
readfile("cool.txt");
// Output cool.txt whole content
It behave differently to file_get_contents from this view.
#!/usr/bin/php
<?php
file_get_contents("js.txt");
// No output!
$cool = file_get_contents("js.txt");
echo $cool;
// Output cool.txt
I know that ob_start turns on output buffering, but I don't fully understand what it means. To me it means that it just stops outputting the script data.
Is this true? How does the browser output data in this case, do I have to use ob_end_flush() to turn it off in the end?
Since ob_gzhandler compresses web pages, how do browsers handle these pages?
I have seen ob_start("gzhandler") in code, since ob_gzhandler compresses web pages, what does ob_start("gzhandler") mean and how does it apply to both functions?
All help appreciated!
Output buffering means that instead of writing your output directly to the stdout stream, it is instead written to a buffer.
Then when the script finishes (or when you call ob_end_flush()), the contents of that buffer are written to stdout.
Using ob_gzhandler transforms the contents of the buffer before writing it to stdout, such that it is gzip compressed. (Browsers which support gzip compression reverse this on the opposite end, decompressing the content.)
Ok, let me explain it like this,
It is only one of the uses of the buffer system but I think it's kinda cool.
first I want you to look to this animation.
Operating System Start
When you have a php script that has a level based structure like this, for example you may write:
Connection established to database server..
Database selected : my_database
Data query started
Data query ended (found:200 rows)
...
etc. but if you don't use output buffering and flushing, you will see these lines when all of your script execution ends. But, when the thought is "I want to see what my script is doing when!", you first need to..
Sorry you first need to set implicit_flush to "on" at your php.ini file and restart your apache server to see all of this.
second, you need to open the output buffering (shorthand "ob") by "ob_start();", and then,
place anywhere on your code "echo" statements and after that "ob_flush();" commands to see your script running on realtime.
Later, it is also used for file based static content buffering like this:
place ob_start() at the start of your page (or the start of content you want to capture)
place ob_end_flush() at the end of your page (or the end of content you want to capture);
then $my_var = ob_get_contents(); to get all the HTML output that server creates and sends to the client into my_var variable and then use it as you want. Mostly it's saved to a file and by checking the file's last modification date, it's used as a static buffering.
I hope I could light some bulbs on your mind.
Can anyone explain why I am receiving the following error?
In the code, if the echo $gz; is commented out I receive no error (but also no output!), if it isn't I get (from Firefox),
Content Encoding Error
The page you
are trying to view cannot be shown
because it uses an invalid or
unsupported form of compression.
Thanks for your help, here's the code:
ob_start('ob_gzhandler') OR ob_start();
echo 'eh?';
$gz = ob_get_clean();
echo $gz;
The output of your application should only contain one output encoding. If you have multiple chunks that are encoded differently, then the browser will get a result that it is impossible to work with. Hence the encoding error.
Kohana itself makes already use of the output buffer. If you want to combine that with your ob_gzhandler output buffer, you need to start your buffer before kohana initialized it's own. That's because output buffer are stackable. When kohana has finished it's output buffering, yours will apply:
ob_start('ob_gzhandler'); # your buffer:
ob_starts and ends by kohana
So whenever kohana has done some output, these chunks will get passed on into your output callback (ob_gzhandler()) and will be gz-encoded.
The browser should then only get gz-encoded data as it was the output buffer at the topmost level.
Using ob_gzhandler and manually echo'ing the buffer
If you make use of ob_start('ob_gzhandler') to let PHP deal with the compression and you then echo ob_get_clean(), you will create an unreliable output. That's related to how the compression togther with output buffering works:
PHP will buffer chunks of output. That means, PHP starts to compress the output but keeps some bytes to continue compressing. So ob_get_clean() returns the so-far compressed part of the buffer. Often that result is not complete.
To deal with that, flush the buffer first:
ob_start('ob_gzhandler') OR ob_start();
echo 'eh?';
ob_flush();
$gz = ob_get_clean();
echo $gz;
And ensure you don't have any more output after that.
If you would have PHP reached the end of your script, it would have taken care of that: Flushing and outputting.
Now you need to manually call ob_flush() to explicitly make PHP push the buffer through the callbacks.
Inspecting HTTP Compression Problems with Curl
As firefox will return an error, another tool to inspect what's causing the encoding error is needed. You can use curl to track what's going on:
curl --compress -i URL
Will request the URL with compression enabled while displaying all response headers and the body unencoded. This is necessary as PHP transparently enables / disables compression of the ob_gzhandler callback based on request headers.
A response also shows that PHP will set the needed response headers as well. So no need to specify them manually. That would be even dangerously, because only by calling ob_start('ob_gzhandler') you can not say if compression is enabled or not.
In case the compression is broken, curl will give an error description but would not display the body.
Following is such a curl error message provoked with an incompletely generated output by a faulty php script:
HTTP/1.1 200 OK
X-Powered-By: PHP/5.3.6
Content-Encoding: gzip
...
curl: (23) Error while processing content unencoding: invalid code lengths set
By adding the --raw switch, you can even peak into the raw response body:
curl --compress --raw -i URL
That can give an impression what's going wrong, like uncompressed parts within the body.
This is what phpharo does:
/** output buffring */
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
ob_start('ob_gzhandler'); ob_start();
}
else
{
ob_start();
}
I am having a php file which executes some code to generate a html file.Its like I m having a form from which some data will be posted to x.php file, which gives a output(a webpage). I want to save that output in a html file.What the most efficient way of doing this.?
EDIT
I want to save it on sever side. Actually the thing is i want to create pdf file for that.. I wrote everything else.Now the thing is i want to save the output in a html page.So that i can convert it into pdf file..
Try something like this:
// Start output buffering
ob_start();
// run code in x.php file
// ...
// saving captured output to file
file_put_contents('filename.htm', ob_get_contents());
// end buffering and displaying page
ob_end_flush();
If you cannot use the ob_* functions, you can also write the form to a variable and then save that variable.
Look at ob functions (see http://php.net/manual/en/function.ob-start.php) that allows you to capture every output (echo, print, etc...) from the page.
using ob_* functions such as ob_get_contents(), a php script can catch it's output.
probably with ob_start and output_callback see http://php.net/manual/en/function.ob-start.php