Example 1
| The code is as follows: |
Copy code |
|
Function download ($ file_url, $ new_name = ''){
If (! Isset ($ file_url) | trim ($ file_url) = ''){
Return '20140901 ';
}
If (! File_exists ($ file_url) {// check whether the file exists
Return '20140901 ';
}
$ File_name = basename ($ file_url );
$ File_type = explode ('.', $ file_url );
$ File_type = $ file_type [count ($ file_type)-1];
$ File_name = trim ($ new_name = '')? $ File_name: urlencode ($ new_name). '.'. $ file_type;
$ File_type = fopen ($ file_url, 'r'); // open the file
// Input file tag
Header ("Content-type: application/octet-stream ");
Header ("Accept-Ranges: bytes ");
Header ("Accept-Length:". filesize ($ file_url ));
Header ("Content-Disposition: attachment; filename =". $ file_name );
// Output file content
Echo fread ($ file_type, filesize ($ file_url ));
Fclose ($ file_type );
} |
Example 2
The following php code can solve the problem:
| The code is as follows: |
Copy code |
<?
If (empty ($ _ GET ['filename']) | empty ($ _ GET ['filedir']) | empty ($ _ GET ['fileid']) {
Echo '<script> alert ("illegal connection! "); Location. replace (" index. php ") </script> '; exit ();
}
$ File_name = $ _ GET ['filename'];
$ File_dir = $ _ GET ['filedir'];
$ FileId = $ _ GET ['fileid'];
$ File_dir = $ file_dir ."/";
If (! File_exists ($ file_dir. $ file_name) {// check whether the file exists
Echo "file not found ";
Exit;
} Else {
$ File = fopen ($ file_dir. $ file_name, "r"); // open the file
// Input file tag
Header ("Content-type: application/octet-stream ");
Header ("Accept-Ranges: bytes ");
Header ("Accept-Length:". filesize ($ file_dir. $ file_name ));
Header ("Content-Disposition: attachment; filename =". $ file_name );
// Output file content
Echo fread ($ file, filesize ($ file_dir. $ file_name ));
Fclose ($ file );
Exit ();
}
?> |
Direct File Download
| The code is as follows: |
Copy code |
<? Php
$ File = get_file_address (); // the actual address of the file (url is supported, but url is not recommended)
If (file_exists ($ file )){
Header ('content-Description: File Transfer ');
Header ('content-Type: application/octet-stream ');
Header ('content-Disposition: attachment; filename = '. basename ($ file ));
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 ($ file ));
Ob_clean ();
Flush ();
Readfile ($ file );
Exit;
}
?>
|
Tips: The header function can not only download files, but also has many other functions, such as sending status information such as 404,301.
Note: Before using the header, we must have no output before the header; otherwise, an error will be reported.