简体   繁体   English

如何在php中下载不存在的文件

[英]How can I download a non-existing file in php

I want to create a file on-the-fly and send it to the browser instead of the php site. 我想即时创建文件并将其发送到浏览器而不是php站点。 I think I need to use the Header-Function, but how do I do that? 我想我需要使用Header-Function,但是我该怎么做? Can anyone tell me that? 谁能告诉我?

<?php
header('Content-type: text/plain');
header('Content-disposition: attachment; filename=hello.txt');
echo "Hello world";
?>

It's very, very difficult to understand what you're saying — what I think you're saying is you want a PHP script to make a client download its output instead of displaying it without creating a file. 很难理解您的意思-我想您在说的是,您希望PHP脚本让客户端下载其输出,而不是不创建文件就显示它。 If that's what you're trying to do, you can use this code: 如果这是您要尝试的操作,则可以使用以下代码:

header("Content-Disposition: attachment; filename=my_file.txt");

If you need to make some data to be downloaded as regular file then you need to say to Browser that the content you gonna send must be downloaded instead as displayed on the browser as a regular HTML. 如果需要将某些数据作为常规文件下载,则需要对浏览器说,必须下载要发送的内容,而不是像常规HTML那样在浏览器上显示。 To to do that you can use the header. 为此,您可以使用标题。 For example: if you need to get a .csv file dinamicly generated by PHP then you need to insert this lines of code before display any data on the page: 例如:如果需要获取由PHP动态生成的.csv文件,则需要插入以下代码行,然后才能在页面上显示任何数据:

    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=report.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo 'data1,data2,data3...';

Make sure you don't send any data to browser before setting any header parameter. 在设置任何标头参数之前,请确保没有将任何数据发送到浏览器。

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

相关问题 如何使包配置将其不存在的键合并到 Laravel 7.x 中的应用程序配置文件中? - How can I make the package config merge it's non-existing keys into the app config file in laravel 7.x? Apache 2.4 + PHP-FPM,如何为不存在的php文件设置错误页面 - Apache 2.4 + PHP-FPM, how to set error page for non-existing php file 如何通过Apache指令使PHP处理不存在的文件请求? - How to make PHP handle a non-existing file request via Apache directives? 为什么我试图写的文件“不存在”? - Why is the file I am attempting to write “non-existing”? 如何在PHP中处理MongoDB find()的不存在的值调用 - How to handle non-existing value call for MongoDB find() in PHP PHP自动装带器:忽略不存在的包含 - PHP autoloader: ignoring non-existing include CodeIgniter 读取不存在的文件 - CodeIgniter reads non-existing file 当我尝试将电子邮件发送到不存在的电子邮件时,php邮件程序未显示错误 - Php mailer not displaying an error when I try to send email to a non-existing email 如何在PHP中下载现有文件 - How to download existing file in PHP 如何使用PHP搜寻标记,检查图像是否存在并替换不存在的路径? - How to crawl markup with PHP, check if images exists and replace non-existing paths?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM