简体   繁体   中英

How to collect file and save on server with PHP

I know this similar question is asked before, but I can't find a solution to my specific problem. I have this code, and it saves to a file and downloads it immediately to the desktop when run from the browser. But I need it to save it on a server. How do I do this with this specific code?

Do I need to save the file into a variable eg $files first?

<?php


header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download"); 
header("Content-Disposition: attachment;filename=export_".date('n-j-Y').".xls "); 
header("Content-Transfer-Encoding: binary ");

exit();

?>  

Here's some normal code:

<?php
echo "hey F4LLCON!";
?>

Executed, it behaves like we expect:

% php output.php 
hey F4LLCON!

Now I'll modify it to add output buffering and save to the file and write to stdout (using regular echo calls!):

<?php
ob_start();
echo "hey F4LLCON!";
$output_so_far = ob_get_contents();
ob_clean();
file_put_contents("/tmp/catched.txt", $output_so_far);
echo $output_so_far;
?>

After executing, the output in the file catched.txt is equal to what we got earlier (and still get) on stdout:

hey F4LLCON!

Now I'll modify it again to show how generators from PHP 5.5 will provide you with an elegant solution that doesn't need to sacrifice performance (the previous solution requires you to save all the intermediate content in one giant output buffer):

<?php
$main = function() {
    yield "hey F4LLCON!";
};
$f = fopen("/tmp/catched2.txt", "wb");
foreach ($main() as $chunk) { fwrite($f, $chunk); echo $chunk; }
fclose($f);
?>

We aren't storing everything in one giant buffer, and we can still output to file and stdout simultaneously.

If you don't understand generators, here's a solution where we pass a callback "print" function to main(), and that function is used every time we want to output (only one time here).

<?php
$main = function($print_func) {
    $print_func("hey F4LLCON!");
};
$f = fopen("/tmp/catched3.txt", "wb");
$main(function($output) use ($f) {
    fwrite($f, $output);
    echo $output;
});
fclose($f);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM