简体   繁体   English

如何使用PHP收集文件并保存在服务器上

[英]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? 我是否需要先将文件保存到变量中,例如$files

<?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!): 现在,我将对其进行修改以添加输出缓冲并保存到文件中并写入stdout(使用常规的echo调用!):

<?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: 执行后,在catched.txt文件中的输出等于我们在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 5.5的生成器将如何为您提供一种优雅的解决方案,而无需牺牲性能(以前的解决方案要求您将所有中间内容保存在一个巨大的输出缓冲区中):

<?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. 我们不会将所有内容存储在一个巨型缓冲区中,我们仍然可以同时输出到文件 stdout。

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). 如果您不了解生成器,则可以使用以下解决方案:将回调“ print”函数传递给main(),并且每次我们要输出时都使用该函数(此处仅一次)。

<?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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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