如何下载 php 中的文件
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 静态值。当我 运行 上面的代码然后它继续其他条件。我认为,上面的代码没有采用项目的完整路径。如果我将图片放在同一个文件夹中,它就会下载。
首先确保 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));
?>
要成功下载,文件目录必须存在。但是我认为添加目录存在性检查是低效的,因为我认为您已经知道在哪里保存您正在下载的文件。
我想下载 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 静态值。当我 运行 上面的代码然后它继续其他条件。我认为,上面的代码没有采用项目的完整路径。如果我将图片放在同一个文件夹中,它就会下载。
首先确保 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));
?>
要成功下载,文件目录必须存在。但是我认为添加目录存在性检查是低效的,因为我认为您已经知道在哪里保存您正在下载的文件。