php写文件收费下载代码,php实现文件下载代码
时间: 2024-02-26 20:58:45 浏览: 24
以下是 PHP 实现文件下载的代码示例:
```php
<?php
$file = 'path/to/file'; // 文件路径
$filename = 'filename.extension'; // 文件名和扩展名
// 检查文件是否存在
if (file_exists($file)) {
// 设置 HTTP 响应头
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
// 读取文件并输出到 HTTP 响应体
readfile($file);
exit;
} else {
echo 'File not found.';
}
?>
```
你可以将上述代码保存为 .php 文件并部署到你的服务器上,替换 `$file` 和 `$filename` 变量为你的文件路径和文件名,即可实现文件下载。
相关问题
php下载文件显示进度条代码
这是一个比较简单的 PHP 代码,可以显示下载文件的进度条:
```
$file_size = filesize($file);
$downloaded = 0;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . $file_name);
header("Content-Length: " . $file_size);
while(!feof($file)) {
$buffer = fread($file, 2048);
echo $buffer;
flush();
$downloaded += strlen($buffer);
$progress = intval($downloaded / $file_size * 100);
echo "<script>document.getElementById('progress').innerHTML='$progress%';</script>";
ob_flush();
flush();
}
```
这段代码将文件的大小读入,然后每次读入 2KB 的数据,并将其输出到浏览器。同时,进度条的进度也会随着下载的进度更新。
用PHP生成解决文件下载跨域的代码
在 PHP 中,可以使用 `header` 函数来设置响应头部,从而解决文件下载时的跨域问题。以下是一个示例代码,可以生成解决文件下载跨域的 PHP 代码:
```php
$fileUrl = 'https://example.com/file.pdf'; // 文件 URL
$fileName = 'file.pdf'; // 下载后的文件名
// 设置响应头部
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Access-Control-Allow-Origin: https://pdfh5.com'); // 允许 pdfh5.com 域名跨域访问该资源
// 读取文件内容并输出到客户端
readfile($fileUrl);
```
上述代码中,`$fileUrl` 变量表示要下载的文件 URL,`$fileName` 变量表示文件下载后保存的文件名。使用 `header` 函数设置响应头部,其中 `Content-Description` 表示文件传输描述、`Content-Type` 表示文件类型、`Content-Disposition` 表示文件下载的方式和保存的文件名,`Access-Control-Allow-Origin` 表示允许跨域访问的域名。最后使用 `readfile` 函数读取文件内容并输出到客户端。
需要注意的是,为了确保安全性,建议仅允许指定的域名或 IP 地址跨域访问该资源,避免使用通配符 `*` 来允许任何域名或 IP 地址跨域访问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)