如何强制文件在PHP中下载

编程入门 行业动态 更新时间:2024-10-26 08:23:57
本文介绍了如何强制文件在PHP中下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有图像列表,我想要一个下载链接与每个图像,以便用户可以下载图像。

I have list of images and I want a "Download" link along with every image so that user can download the image.

所以有人可以指导我如何为php中的任何文件提供下载链接?

so can someone guide me How to Provide Download link for any file in php?

编辑

我希望在点击下载链接时显示一个下载面板,我不想导航到浏览器中显示的图像

I want a download panel to be displayed on clicking the download link I dont want to navigate to image to be displayed on the browser

推荐答案

如果您想强制下载,可以使用以下内容:

If you want to force a download, you can use something like the following:

<?php // Fetch the file info. $filePath = '/path/to/file/on/disk.jpg'; if(file_exists($filePath)) { $fileName = basename($filePath); $fileSize = filesize($filePath); // Output headers. header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName); // Output file. readfile ($filePath); exit(); } else { die('The provided file path is not valid.'); } ?>

如果您只需使用正常链接链接到此脚本,该文件将被下载。

If you simply link to this script using a normal link the file will be downloaded.

顺便提一句,上面的代码片段需要在页面开始执行(在任何标题或HTML输出发生之前)。还要注意,如果你决定创建一个基于这个功能来下载任意文件 - 你需要确保你阻止目录遍历( realpath 是方便的),只允许从定义的区域下载等,如果您接受$ _GET或$ _POST的输入。

Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.

更多推荐

如何强制文件在PHP中下载

本文发布于:2023-11-01 20:37:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!