Home > Article > Backend Development > How to save downloaded files in php
php method to save downloaded files: 1. Download files through the "function downfile(){...}" method; 2. Save and download through the header function.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
php download and save the file and save it to the local Two implementation methods
The download here refers to the pop-up download prompt box.
The first method:
<?php function downfile() { $filename=realpath("resume.html"); //文件名 $date=date("Ymd-H:i:m"); Header( "Content-type: application/octet-stream "); Header( "Accept-Ranges: bytes "); Header( "Accept-Length: " .filesize($filename)); header( "Content-Disposition: attachment; filename= {$date}.doc"); echo file_get_contents($filename); readfile($filename); } downfile(); ?>
or (recommended this method, personal test is feasible, others have not been tested)
<?php function downfile($fileurl) { ob_start(); $filename=$fileurl; $date=date("Ymd-H:i:m"); $size=readfile($filename); header( "Content-type: application/octet-stream "); header( "Accept-Ranges: bytes "); header( "Content-Disposition: attachment; filename= {$date}.doc"); header( "Accept-Length: " .$size); } $url="url地址"; downfile($url); ?>
The second method:
<?php function downfile($fileurl) { $filename=$fileurl; $file = fopen($filename, "rb"); Header( "Content-type: application/octet-stream "); Header( "Accept-Ranges: bytes "); Header( "Content-Disposition: attachment; filename= 4.doc"); $contents = ""; while (!feof($file)) { $contents .= fread($file, 8192); } echo $contents; fclose($file); } $url="url地址"; downfile($url); ?>
PHP implements two methods for downloading files. Share it so friends who may find it useful can take a look.
Method 1:
<?php /** * 下载文件 * header函数 * */ header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($filepath)); header('Content-Transfer-Encoding: binary'); header('Expires: 0′); header('Cache-Control: must-revalidate, post-check=0, pre-check=0′); header('Pragma: public'); header('Content-Length: ' . filesize($filepath)); readfile($file_path); ?>
Understand the usage of header function in php.
Method 2:
<?php //文件下载 //readfile $fileinfo = pathinfo($filename); header('Content-type: application/x-'.$fileinfo['extension']); header('Content-Disposition: attachment; filename='.$fileinfo['basename']); header('Content-Length: '.filesize($filename)); readfile($thefile); exit(); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to save downloaded files in php. For more information, please follow other related articles on the PHP Chinese website!