This article mainly introduces a simple example of php file downloading. For more information, see
This article mainly introduces a simple example of php file downloading. For more information, see
The Code is as follows:
Public function downloads ($ name ){
$ Name_tmp = explode ("_", $ name );
$ Type = $ name_tmp [0];
$ File_time = explode (".", $ name_tmp [3]);
$ File_time = $ file_time [0];
$ File_date = date ("Y/md", $ file_time );
$ File_dir = SITE_PATH. "/data/uploads/$ type/$ file_date /";
If (! File_exists ($ file_dir. $ name )){
Header ("Content-type: text/html; charset = UTF-8 ");
Echo "File not found! ";
Exit;
} Else {
$ File = fopen ($ file_dir. $ name, "r ");
Header ("Content-type: application/octet-stream ");
Header ("Accept-Ranges: bytes ");
Header ("Accept-Length:". filesize ($ file_dir. $ name ));
Header ("Content-Disposition: attachment; filename =". $ name );
Echo fread ($ file, filesize ($ file_dir. $ name ));
Fclose ($ file );
}
}
Example 2: Download the code
Generally, URLs are called to download files. However, this method cannot be used to identify files opened by ie, such as downloading an image or html webpage, in this case, programming is required. The following php code can be used:
The Code is as follows:
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 ();
}
?>