如何使用PHP收集文件并保存在服务器上 [英] How to collect file and save on server with PHP

查看:266
本文介绍了如何使用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?

我是否需要将文件保存到变量中,例如$files首先?

Do I need to save the file into a variable e.g. $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();

?>  

推荐答案

以下是一些常规代码:

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

已执行,其行为与我们期望的一样:

Executed, it behaves like we expect:

% php output.php 
hey F4LLCON!

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

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

执行后,文件catched.txt中的输出等于我们在stdout上获得(并且仍然获得)的输出:

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

hey F4LLCON!

现在,我将再次对其进行修改,以显示PHP 5.5的生成器将如何为您提供一种优雅的解决方案,而无需牺牲性能(以前的解决方案要求您将所有中间内容保存在一个巨大的输出缓冲区中) :

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

我们没有将所有内容存储在一个巨型缓冲区中,我们仍然可以同时输出到文件 stdout.

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

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

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

这篇关于如何使用PHP收集文件并保存在服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆