Home >Backend Development >PHP Tutorial >How to download various files in php_PHP tutorial

How to download various files in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:49:31767browse

If we only use download or js's window.location = 'file path/file name', and the file type is recognized by the browser , then the browser will directly open the file instead of popping up a download box to download the file, such as '.txt', '.conf', '.bin' files, etc. Of course, js's document.execCommand('SaveAs','mycodes.txt') (the second parameter is the file name to be saved as) can also be downloaded, but its compatibility is not good and it is invalid under Firefox. At this time, if your environment supports the php language, then you can use header() to download files:

Let’s look at a simple example first:

There are two files index.php, test.php and the downloadable file adam.txt in the same directory:

test.php file content:

$filename = $filename = 'adam.txt';
echo "Download";

?>

index.php file content:

$filename = $_REQUEST['filename'];

header("Content-Type:text/plain");
header('Content-Disposition:attachment;filename='.$filename);
header('Content-Transfer-Encoding: binary');
readfile($filename);

?>

When you open test.php and click download, the adam.txt file will be downloaded.

Similarly, we can also download .jpg, .zip, .rar, .pdf and other files. In this case, we only need to change the header ("Content-Type: text/plain") in index.php slightly. Make modifications, such as shown below

header("Content-Type:application/zip");//zip or rar

header("Content-Type:application/pdf");//pdf

header("Content-Type:image/jpeg");//image

header("Content-Type:audio/mpeg");


Excerpted from adamboy

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478349.htmlTechArticleIf we only use a href=file path/file name download/a or js window.location = file path / file name, and the file type is recognized by the browser, then the browser will directly open...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn