How to save php file as csv file? - php

script1.php returns results:
helen,hunt
jessica,alba
script2.php returns results:
bradley,cooper
brad,pitt
script.php looks like this
<?php
echo "name,surname";
require_once('script1.php');
require_once('script2.php');
?>
and will return
name,surname
helen,hunt
jessica,alba
bradley,cooper
brad,pitt
Question
Maybe this is obvious to someone, but I am struggling for a while how to save this php file: script.php as csv file? script1.php and script2.php both produce result over while loop, so I would be able to save results as array inside of a while loop however hopefully someone will offer an easy solution to my original question.

If I get it right, you are trying to save the output of those scripts to a CSV file.
Try doing:
ob_start();
echo "name,surname";
require_once('script1.php');
require_once('script2.php');
$result = ob_get_contents();
file_put_contents('filename.csv', $result)
You can also take a look at fputcsv: http://php.net/manual/en/function.fputcsv.php

If your question is how to do it having the access to the terminal, then just execute it
php -f script.php > file.csv
If you want to do it from the script, you can use output buffering. It will be along the lines of:
<?php
ob_start();
echo "name,surname";
require_once('script1.php');
require_once('script2.php');
$size=ob_get_length();
if ($size > 0)
{
$content = ob_get_contents();
// save $content to file here
ob_clean();
}
?>
Or, alternatively, if you can change script1.php and script2.php, make them open the file for appending (fopen('fname.csv', 'a')), and write to that file, it will result in rows from both of them written to the file without overwriting each other.

Related

Get current page name with file created by a PHP file

So I have a page called create.php that creates another php file called "1". In this php file called "1". I was hoping to use
<?php echo $_SERVER['PHP_SELF'];?>
or
<?php $path = $_SERVER["SCRIPT_NAME"];echo $path;?>
To create a link that would take the number of the page and +1 it. When I do both of these functions instead of getting what I would think I would get, "1", I get "create", the page that it was created with. I'm quite dumbfounded by why this is happening, the code is most definitely on "1" and I even double checked to make sure create made a file and that I was on it so why does it think the current page is "create"?
Code being used
<?php
// start the output buffer
ob_start(); ?>
<?php echo $_SERVER['PHP_SELF'];?>
<?php
// open the cache file "cache/1" for writing
$fp = fopen("cache/1", 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
?>
You split the code in pieces and you probably have a wrong idea about what happens and what will be written in cache/1. Your code is the same as the following:
<?php
// start the output buffer
ob_start();
// echo the path of the current script
echo $_SERVER['PHP_SELF'];
// open the cache file "cache/1" for writing
$fp = fopen("cache/1", 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
I removed the closing PHP tag (?>) when it was followed by an open PHP tag (<?php).
Now it should be clear that, without output buffering, the script create.php display its own path relative to the document root. The output buffering captures the output and puts it into file cache/1.
You don't even need output buffering for this. You can simply remove all the calls to ob_* functions, remove the echo() line and use:
fwrite($fp, $_SERVER['PHP_SELF']);
It's clear that this is not your goal. You probably want to generate a PHP file that contains the following content:
<?php echo $_SERVER['PHP_SELF'];?>
This is as simple as it putting this text into a string and writing the string to the file:
<?php
$code = '<?php echo $_SERVER["PHP_SELF"];?>';
$fp = fopen("cache/1", 'w');
fwrite($fp, $code);
fclose($fp);
You can even use the PHP function file_put_contents() and all the code you posted in the question becomes:
file_put_contents('cache/1', '<?php echo $_SERVER["PHP_SELF"];?>');
If you need to put a bigger block of PHP code in the generated file then you can use the nowdoc string syntax:
$code = <<<'END_CODE'
<?php
// A lot of code here
// on multiple lines
// It is not parsed for variables and it arrives as is
// into the $code variable
$path = $_SERVER['PHP_SELF'];
echo('The path of this file is: '.$path."\n");
$newPath = dirname($path).'/'.(1+(int)basename($path));
echo('The path of next file is: '.$newPath."\n");
// That's all; there is no need for the PHP closing tag
END_CODE;
// Now, the lines 2-11 from the code above are stored verbatim in variable $code
// Put them in a file
file_put_contents('cache/1', $code);

Is is possible to get file output buffer without including the file?

Is it possible to get file output buffer string to execute the file in background instead of including it?
Right now this is the only way which I have seen. See code below;
ob_start();
include($file);
$html = ob_get_contents();
ob_end_clean();
But I have list of files which I don't want to include. I just want to execute the file in background process for getting output buffer string.
Can anyone please help me on it?
Thanks
Smac
If your file is php you need to use include.For multiple files you can use function like this I found here
function include_multi($files) {
$files = func_get_args();
foreach($files as $file)
include($file);
}
And call it with
include_multi("one.php", "two.php", ..);
Also If you want plain file contents(No need to execute file) you can use
file_get_contents or readfile

Store PHP Output To File?

I'm working on a cron php script which will run once a day. Because it runs this way, the output from the file can't be seen.
I could literally write all the messages I want into a variable, appending constantly information I want to be written to file, but this would be very tedious and I have a hunch not necessary.
Is there a PHP command to tell the write buffer to write to a log file somewhere? Is there a way to get access to what has been sent to the buffer already so that I can see the messages my script makes.
For example lets say the script says
PHP:
<?
echo 'hello there';
echo 'hello world';
?>
It should output to a file saying: 'hello therehello world';
Any ideas? Is this possible?
I'm already aware of
file_put_contents('log.txt', 'some data', FILE_APPEND);
This is dependent upon 'some data', when I don't know what 'some data' is unless I put it in a variable. I'm trying to catch the results of whatever PHP has outputted.
You may want to redirect your output in crontab:
php /path/to/php/file.php >> log.txt
Or use PHP with, for example, file_put_contents():
file_put_contents('log.txt', 'some data', FILE_APPEND);
If you want to capture all PHP output, then use ob_ function, like:
ob_start();
/*
We're doing stuff..
stuff
...
and again
*/
$content = ob_get_contents();
ob_end_clean(); //here, output is cleaned. You may want to flush it with ob_end_flush()
file_put_contents('log.txt', $content, FILE_APPEND);
you can use ob_start() to store script output into buffer. See php documentation ob_get_clean
<?php
ob_start();
echo "Hello World";
$out = ob_get_clean();
$out = strtolower($out);
var_dump($out);
?>
If You're using cron I suppose that You run this on a Unix machine so:
One of approach is to write everything You want to stdout stream so in Unix You may grab this output to a file:
in php script:
$handle = fopen("php://stdout","w");
fwrite($handle,"Hello world"); // Hello world will be written to console
in cron job grab this output to a file:
#hourly php /var/www/phpscript.php >> /path/to/your/outputfile.txt
Notice: >> operator will append to a file and > operator will overwrite file by new data. File will be created automatically by first write
So everything you put to fwrite call as second argument will be placed in /path/to/your/outputfile.txt
You may call fwrite as many time as you want. Don't forget to close handler by fclose($handle);

How to get multiple PHP files output into a single a file for further usage of those output?

I am trying to get the output of multiple PHP files into a single PHP file where I can save them into different variables for further usage.
For a single PHP file, I used include and it works well. But for multiple files I don't know what to do.
Do you have any experiences or advices on how to achieve this ?
I had three php files called a.php,b.php and c.php. Now in each file i am echoing an array as output. For first php file i done like below to save the output of that in fourth php file called d.php
ob_start();
include_once('a.php');
$output= ob_get_clean();
echo "<pre>";print_r($output);
Now what to do for getting second and third php files outputs.
I think this is what you want
<?php
$string1 = get_include_contents('somefile1.php');
$string2 = get_include_contents('somefile2.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
?>

Php problem eval/html/php

I've been writing a php/html page encoder/decoder... I know it already exists but it's a university project so go on XDDD
I encode the pages that I want to protect let's say hypothetically with base64_encode and when I receive a request of any pages I have a loader that reads the coded page, decrypts it and with eval executes it. The real problems arise when I try to decrypt and execute a mixed php/html page. Obviously eval can't execute html code so my question is do I really become crazy about splitting the page executing the php code and print the html? And also if I include an encoded php or php/html page do I really have to reuse the method up here?
I hope someone can really help me because i have a week left before the deadline and I can't change the project at this point.
chris here the function and the fisrt calling in $param[0] i've got the filename called
function MyInclude($filename)
{
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($temp_filename , 'w+');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
$tmp=file_get_contents($filename);
$data=MCrypt_Decode($tmp,'PFL_EPU_V100_mia');
fwrite($handle,$data );
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
}
MyInclude($param[0]);
the $param[0] file here
<?php
session_start();
$_SESSION['title']='Home';
MyInclude("header.php");
?>
<body>
sono il body <?php echo APP_PATH; ?>
</body>
<?
echo "boss";
MyInclude("footer.php");
?>
any idea about it??? or you need some other code??? let me know T_T
Mike
You can eval() a string that contains mixed html and php, just so long as the tags are included.
http://php.net/manual/en/function.eval.php
When eval() encounters a php close tag (?>), it will stop trying to treat it as php code and just echo everything out until it comes to a php open tag.
The typical solution to your problem is something like this:
$file = ... //Your decoded php/html code here
$file = '?>' . $file; //Add a close tag to the beginning;
ob_start();
eval($file);
$output = ob_get_clean();
echo $output; //Or do something else with it... really, if you're
//just going to be echoing it you can skip the output buffering
Is it possible to decrypt the page, write it to a file, then include it? That would let the PHP interpreter do what it does best - interpret PHP documents. That will include HTML/PHP combinations without relying on eval.
The outline of that would be:
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($filename , 'w');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
fwrite($handle, $decrypted_data);
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include_once($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
Function references
fopen: http://us2.php.net/manual/en/function.fopen.php
fwrite: http://us2.php.net/manual/en/function.fwrite.php
fclose: http://us2.php.net/manual/en/function.fclose.php
ob_start: http://us2.php.net/manual/en/function.ob-start.php
ob_get_contents: http://us2.php.net/manual/en/function.ob-get-contents.php
ob_end_clean: http://us2.php.net/manual/en/function.ob-end-clean.php
unlink: http://www.php.net/manual/en/function.unlink.php
You will need dump the decoded file to another file and include(); it. The eval approach will not work because it will exit with a parse error if the first item in the file is not either an opening <?php tag, or a valid bit of PHP code.
More than this, you will need to find/replace any occurences of include(), require(), include_once(), and require_once() within the encrypted file with a different function, to ensure you don't try to execute another encrypted file before it has been decrypted. You could do this at execution (ie decryption) time, but it would be much better to it a encryption time, to minimise the time required to pre-fetch the code before it is executed.
You can define these customised functions to decrypt a file and include/require it in your loader script.
Your problem description is a bit vague however your problem seems to be solvable with output buffering.
Have you tried decrypting the page, then parsing the text to split out anything between and then only executing that code?

Categories