PHP output buffering to text file - php

I am having trouble with an update script. It runs for a few hours so I would like it to output live to a text file.
I start the document with
ob_start();
Then within the while loop (as it iterates through the records of the database) I have this
$size=ob_get_length();
if ($size > 0)
{
$content = ob_get_contents();
logit($contents);
ob_clean();
}
And finally the logit function
function logit($data)
{
file_put_contents('log.txt', $data, FILE_APPEND);
}
However the log file remains empty. What am I doing wrong?

try
logit($content);
// ^^ Note the missing s

$contents is not the same variable as $content.

For anyone coming here looking for a function for this, I wrote a nice one today:
//buffer php outout between consecutive calls and optionally store it to a file:
function buffer( $toFilePath=0, $appendToFile=0 ){
$status = ob_get_status ();
if($status['level']===1) return ob_start(); //start the buffer
$res = ob_get_contents();
ob_end_clean();
if($toFilePath) file_put_contents($toFilePath, $res, ($appendToFile ? FILE_APPEND : null));
return $res;
}
Sample usage:
buffer(); //start the buffer
echo(12345); //log some stuff
echo(678910);
$log = buffer('mylog.txt',1); //add these lines to a file (optional)
echo('Heres the latest log:'.$log);

Related

Troubles using ob, checking PHP connection lost

First of all, sorry for my probably bad english...
I'm trying to make a script that works only until an event occur or the connection is stopped. I have to work with output buffers (for logging and debugging reasons) but I noticed that after the connection is lost, everything I try to put in the buffer it doesn't appear.
Here I made a scripts to test this behaviour:
<?php
// here I avoid to let the script stops when the connection is lost
// in order to continue with logging, debugging or wathever
ignore_user_abort(true);
// here there is an utility function that flushes the content
// to let us know if the connection is still active
$fnExec = 0; // this is a variable useful for log the script activity
function is_connection_aborted() {
global $fnExec;
$fnExec++;
// now I get the content of all output buffers and store them,
// then I clean and flush the outputs
$obs = 0;
$contents = Array();
while ($level = ob_get_level()) {
$obContent = ob_get_contents();
array_unshift($contents, $obContent);
ob_clean();
ob_end_flush();
$obs++;
}
echo "\r"; // this is needed in order to have at least a character to flush
flush();
$conn = connection_aborted();
// here I start an output buffer to log what's inside the $contents variable
ob_start();
var_dump($contents);
$fh = fopen('test/fn_'.$fnExec.'.txt', 'w');
fwrite($fh, ob_get_clean());
fclose($fh);
// Now I restore the content in all the output buffers
$count = count($contents) - 1;
$index = 0;
do {
ob_start();
echo $contents[$index];
} while (++$index < $obs);
// Finally returns the value of connection_aborted()
return $conn;
}
// I want to start an output buffer here to manage the output of the script
ob_start();
// This is a simple script that run at most for 5 seconds and print an incremental
// number each iteration, after slept 2 seconds.
// It can be stopped aborting the connection!
$start = time();
$attempts = 0;
while (true) {
echo ++$attempts."\r\n";
if (is_connection_aborted() || (time() - $start) > 5) {
break;
}
sleep(2);
}
// Here I get the content of the output buffer
$content = ob_get_clean();
// And finally I log the content in a file
$fh = fopen('test/test_ob.txt', 'w');
fwrite($fh, $content);
fclose($fh);
Now to the test!
I leave the connection opened up to 2 seconds, and so I expect to see only 1-2 iterations and then a final output like '1 2 3' in the 'test/test_ob.txt' file.
The result, instead, is that I have the file 'test/test_ob.txt' empty but also the file log of the fn()'s execution! It seems like every ob_start() after the connection is lost, will be filled with anything!
Why do output buffers work only until the connection is lost? Is the loss of connection really the problem?
Thanks in advance!

How to save html output to .java file from php

This is my html output. from .php file
public class Resource {
public static int cliamer = fgfgfger;
public static int reporting = grgrging;
}
I want to save this to mytext.java how is it possible with php
Something like this:
$myData = "java code goes here";
$fp = fopen('dir/mytext.java', 'w');
fwrite($fp, $myData);
fclose($fp);
Main point of failure here will be the folder's permission.
// beginning of your script
ob_start();
// your script
// end of your script
$data = ob_get_contents();
ob_end_clean(); // or ob_end_flush(); if you also want to output something
file_put_contents(dirname(__FILE__).'/mytext.java', $data);

Issue in my function for include files with template tag

In my own function, First i want to include one html file, Then if in that included file, we find another html file name, i want to merge content of first included file and second included file.
function inc($html){
$include_pattern = "\{\s*include\s*(\(|')\s*([a-zA-Z0-9-.\/-_]+)\s*(\)|')\s*\}";
preg_match_all("/$include_pattern/s",$html,$match);
if($len = count($match[0])){
$i=0;
while($i<$len){
$file = preg_replace("/$include_pattern/s","$2",$match[0][$i]);
ob_start();
include($file);
$output = ob_get_contents();
ob_end_clean();
//$output = $this->inc($output);
$html = str_replace($match[0][$i],$output,$html);
$i++;
}
return $html;
}
}
In this function, if you look at the commented part in the code, i was tried for get content of 2nd included html file. Imagine, if we include 1.html, if in this included file we have 2.html, how we can show content of 2.html and content of 1.html ?
If you look at image in below, its clear for understand current topic. ( i want to get result like "result box" in the image).
I fix issue in my function. There is changed function and work well...
function inc($html){
$include_pattern = "\{\s*include\s*(\(|')\s*([a-zA-Z0-9-.\/-_]+)\s*(\)|')\s*\}";
preg_match_all("/$include_pattern/s",$html,$match);
if($len = count($match[0])){
$i=0;
while($i<$len){
$file = preg_replace("/$include_pattern/s","$2",$match[0][$i]);
ob_start();
include($file);
$output = ob_get_contents();
ob_end_clean();
$html = str_replace($match[0][$i],$output,$html);
$i++;
}
return inc($html);
}else{
return $html;
}
}

How to get include contents as a string? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Execute a PHP file, and return the result as a string
PHP capture print/require output in variable
I am trying to get the contents of an include to a string. Is that possible?
For example, if I have a test.php file:
echo 'a is equal to '.$a;
I need a function, say include_to_string to include the test.php and return what would be output by in in a string.
Something like:
$a = 4;
$string = include_to_string(test.php); // $string = "a is equal to 4"
ob_start();
include 'test.php';
$string = ob_get_clean();
I think is what you want. See output buffering.
ob_start();
include($file);
$contents = ob_get_contents(); // data is now in here
ob_end_clean();
You can do this with output buffering:
function include2string($file) {
ob_start();
include($file);
return ob_get_clean();
}
#DaveRandom points out (correctly) that the issue with wrapping this in a function is that your script ($file) will not have access to variable defined globally. That might not be an issue for many scripts included dynamically, but if it is an issue for you then this technique can be used (as others have shown) outside of a function wrapper.
** Importing variables
One thing you can do is to add a set of data you would like to expose to your script as variables. Think of it like passing data to a template.
function include2string($file, array $vars = array()) {
extract($vars);
ob_start();
include($file);
return ob_get_clean();
}
You would call it this way:
include2string('foo.php', array('key' => 'value', 'varibleName' => $variableName));
and now $key and $variableName would be visible inside your foo.php file.
You could also provide a list of global variables to "import" for your script if that seems clearer to you.
function include2string($file, array $import = array()) {
extract(array_intersect_key($GLOBALS, array_fill_keys($import, 1)));
ob_start();
include($file);
return ob_get_clean();
}
And you would call it, providing a list of the globals you would like exposed to the script:
$foo='bar';
$boo='far';
include2string('foo.php', array('foo'));
foo.php should be able to see foo, but not boo.
You could also use this below but I recommend the above answer.
// How 1th
$File = 'filepath';
$Content = file_get_contents($File);
echo $Content;
// How 2th
function FileGetContents($File){
if(!file_exists($File)){
return null;
}
$Content = file_get_contents($File);
return $Content;
}
$FileContent = FileGetContents('filepath');
echo $FileContent;
Function in PHP manual : file_get_contents

PHP - print content from file after manipulation

I'm struggling trying to read a php file inside a php and do some manipulation..after that have the content as a string, but when I try to output that with echo or print all the php tags are literally included on the file.
so here is my code:
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
$file = file_get_contents($path);
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}
and this will return a string like
<div id="content>
<h2>Here is my title</h2>
<p><? echo "my body text"; ?></p>
</div>
but this will print exactly the content above not compiling the php on it.
So, how can I render this "compilePage" making sure it returns a compiled php result and not just a plain text?
Thanks in advance
function compilePage($page, $path) {
$contents = getMenuFor($page);
ob_start();
include $path;
$contents .= "\n".ob_get_clean();
return $contents;
}
To evaluate PHP code in a string you use the eval function, but this comes highly unadvised. If you have a file containing PHP code, you can evaluate it with include, include_once, require, or require_once depending on your need. To capture the output of an included file - or required, or whichever method - you need to enable output buffering.
You can use output buffering for this, and include the file normally:
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
ob_start();
include $path;
$file = ob_get_contents();
ob_end_clean();
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}
The include() call will include the PHP file normally, and <?php blocks will be parsed and executed. Any output will be captured by the buffer created with ob_start(), and you can get it later with the other ob_* functions.
You need to use include() so it will execute. You can couple this with output buffering to get the return in a string.
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
//output buffer
ob_start();
include($path);
$file = ob_get_contents();
ob_end_clean();
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}

Categories