[英]how to download file in php
我想下载 php 中的图像文件。
<?php
if(isset($_REQUEST["file"])){
$filepath = BASE_URL.'assets/uploads/save_template_images/template1_221594899972.png';
// Process download
if(file_exists($filepath)) {
echo $filepath;
exit;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
die();
} else {
echo $filepath;
exit;
http_response_code(404);
die();
}
}
?>
在我的索引页面中,我有一个锚标记,如果单击锚标记,则运行上面的代码。 我没有显示锚标记,因为我将$filepath static 值放在上面的代码中。 当我运行上面的代码时,它会进入其他条件。 我认为,项目的完整路径并没有被上面的代码所采用。 如果我将图像放在同一个文件夹中,那么它会下载。
首先确保php.ini
文件中的allow_url_fopen
设置已打开。 之后使用此代码下载您的文件:
<?php
$url = 'https://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg';
$file = './files/'.basename($url);
file_put_contents($file, file_get_contents($url));
?>
要成功下载,文件目录必须存在。 但我认为添加目录存在检查效率低下,因为我认为您已经知道在哪里保存正在下载的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.