PHP - 如何下载服务器上的文件

1.应用场景

需要将服务器上的文件,下载到客户端(浏览器)

补充场景: 

PHP如何下载远程服务器上的文件到本地服务器

2.学习/实践

1. 文档

请教PHP如何下载远程服务器上的文件到本地服务器上-php教程-PHP中文网

2. 整理输出

方式有如下几种

2.1 fget()

TBD

2.2 file_get_contents()

TBD

2.3 fopen & fread & fclose

<?php

class Download

{

    /**

     * 下载文件

     * @param $filePath

     */

    public function downloadFile($filePath)

    {

        if (!file_exists($filePath)) {

            echo "下载文件不存在!";

            exit;

        }

        $fileName = basename($filePath);

        $fp = fopen($filePath, "r");

        $fileSize = filesize($filePath);

        //下载文件需要用到的头

        Header("Content-type: application/octet-stream");

        Header("Accept-Ranges: bytes");

        Header("Accept-Length: " . $fileSize);

        Header("Content-Disposition: attachment; filename=" . $fileName);

        $buffer = 1024;

        $fileCount = 0;

        while (!feof($fp) && $fileCount < $fileSize) {

            $fileCon = fread($fp, $buffer);

            $fileCount += $buffer;

            echo $fileCon;

        }

        fclose($fp);

    }

}

// 绝对路径

$filePath = __DIR__ . '\download.json';

// 相对路径,一直提示文件不存在!

// $filePath = 'download.json';

$donwload = new Download();

$donwload->downloadFile($filePath);

结果如下

代码

https://github.com/ningxiaofa/php-learning/blob/master/文件下载/download.php

2.4 cURL --- 很强大的工具

cURL - 学习/实践_william_n的博客-CSDN博客

后续补充

..。

3.问题/补充

1.关于响应头的content-type的设置

code

<?php

error_reporting(0);

header('Content-Type: text/json');

$key=$_GET['key'];
$handle = fopen ("./hello.txt", "rb");

$contents = "";

do {
    $data = fread($handle, 1024);
    if (strlen($data) == 0) {
        break;
    }
    $contents.= $data;
} while(true);

fclose ($handle);
echo $contents;

如果没有设置Header("Content-type: xxx/xxx");

则默认为 text/html

如果设置,则设置是什么, 便是是什么

header('Content-Type: text/json');

header('Content-Type: text/json123');

所以,可以说,我们有时可以自定义content-type类型, 但是不建议。

请结合具体情况分析~~

4.参考

php如何下载?-php教程-PHP中文网

后续补充

...
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值