Php get the local computer file and download it as _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Tags gtar
Php obtains the local computer file, downloads it, and saves it. To download files in php, we use the readfile () function directly. readfile () can download the server source files, next I will introduce you to the users who download readfile files in php. We use the readfile () function directly, and readfile () can download the server source files, next, I will introduce the methods and performance of downloading files from readfile.

Example 1

The code is as follows:

Header ("Content-Type: text/html; charset = UTF-8 ″);
Header ("Content-type: application/text ");

// The file will be called downloaded.pdf
Header ("Content-Disposition: attachment; filename = log. text ");

// The PDF source is in original.pdf
Readfile(“ptindex_user_profilebasc.html ");

?>

Example 2

The code is as follows:

$ Item = trim ($ _ GET ['filename']). ". txt ";
$ Abs_item = '/usr/home/folder name/'. $ item;
$ Browser = 'ie ';
Header ('content-Type: '. ($ browser = 'Ie' | $ browser = 'Opera ')?
'Application/etetstream': 'application/octet-stream '));
Header ('expires: '. gmdate ('d, d m y h: I: s'). 'gmt ');
Header ('content-Transfer-Encoding: binary ');
Header ('content-Length: '. filesize ($ abs_item ));
If ($ browser = 'Ie '){
Header ('content-Disposition: attachment; filename = "'. $ item .'"');
Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 ');
Header ('pragma: public ');
} Else {
Header ('content-Disposition: attachment; filename = "'. $ item .'"');
Header ('cache-Control: no-Cache, must-revalidate ');
Header ('pragma: no-cache ');
}
@ Readfile ($ abs_item );

You can only download local functions. if you want to download remote functions, you can perform the following operations to remotely download files to local functions in PHP:

The code is as follows:

Echo httpcopy ("/baidu_sylogo1.gif ");

Function httpcopy ($ url, $ file = "", $ timeout = 60 ){
$ File = empty ($ file )? Pathinfo ($ url, PATHINFO_BASENAME): $ file;
$ Dir = pathinfo ($ file, PATHINFO_DIRNAME );
! Is_dir ($ dir) & @ mkdir ($ dir, 0755, true );
$ Url = str_replace ("", "% 20", $ url );

If (function_exists ('curl _ init ')){
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_TIMEOUT, $ timeout );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, TRUE );
$ Temp = curl_exec ($ ch );
If (@ file_put_contents ($ file, $ temp )&&! Curl_error ($ ch )){
Return $ file;
} Else {
Return false;
}
} Else {
$ Opts = array (
"Http" => array (
"Method" => "GET ",
"Header" => "",
"Timeout" => $ timeout)
);
$ Context = stream_context_create ($ opts );
If (@ copy ($ url, $ file, $ context )){
// $ Http_response_header
Return $ file;
} Else {
Return false;
}
}
}
?>

Finally, I will share a class function that supports multiple file downloads.

The code is as follows:

/**
* Usage:
* Require_once 'download. class. php ';
* $ Filepath = './path/filename.html ';
* $ Downname = 'downname.html ';
* $ Down = new download ($ filepath, $ downname );
* Or
* $ Down = new download ();
*
**/
Class download
{
Var $ filepath;
Var $ downname;
Var $ ErrInfo;
Var $ is_attachment = false;
Var $ _ LANG = array (
'Err' => 'error ',
'Args _ empty' => 'Parameter error. ',
'File _ not_exists '=>' The file does not exist! ',
'File _ not_readable '=>' The file is not readable! ',
);
Var $ MIMETypes = array (
'EZ '=> 'application/andrew-inset ',
'Hqx' => 'application/mac-binhex40 ',
'Cpt' => 'application/mac-compactpro ',
'Doc' => 'application/msword ',
'Bin' => 'application/octet-stream ',
'Dms '=> 'application/octet-stream ',
'Lha' => 'application/octet-stream ',
'Lzh '=> 'application/octet-stream ',
'Exe '=> 'application/octet-stream ',
'Class' => 'application/octet-stream ',
'So' => 'application/octet-stream ',
'Dll '=> 'application/octet-stream ',
'Oda '=> 'application/oda ',
'PDF '=> 'application/pdf ',
'AI' => 'application/postscr reject pt ',
'Eps '=> 'application/postscr reject pt ',
'Ps' => 'application/postscr reject pt ',
'Smi' => 'application/smil ',
'Smil '=> 'application/smil ',
'Mfa' => 'application/vnd. mfa ',
'XLS '=> 'application/vnd. ms-excel ',
'Ppt '=> 'application/vnd. ms-powerpoint ',
'Wbxml' => 'application/vnd. wap. wbxml ',
'Wmlc' => 'application/vnd. wap. wmlc ',
'Wmlsc '=> 'application/vnd. wap. wmlscr restart ptc ',
'Bcpio' => 'application/x-bcpio ',
'Vcd' => 'application/x-cdlink ',
'Pgn' => 'application/x-chess-pgn ',
'Cpio' => 'application/x-cpio ',
'CSH' => 'application/x-csh ',
'Dcr '=> 'application/x-ctor ',
'Dir' => 'application/x-ctor ',
'Dxr' => 'application/x-ctor ',
'Dvi '=> 'application/x-dvi ',
'Spl' => 'application/x-futuresplash ',
'Gtar '=> 'application/x-gtar ',
'Hdf' => 'application/x-hdf ',
'Js' => 'application/x-Forwarded Cr limit pt ',
'Skp' => 'application/x-koan ',
'Skd' => 'application/x-koan ',
'Skt' => 'application/x-koan ',
'Skm' => 'application/x-koan ',
'Latex '=> 'application/x-latex ',
'NC '=> 'application/x-netcdf ',
'Cdf' => 'application/x-netcdf ',
'Sh' => 'application/x-sh ',
'Shar '=> 'application/x-shar ',
'Swf '=> 'application/x-shockwave-Flash ',
'Sit '=> 'application/x-stuffit ',
'Sv4cpio '=> 'application/x-sv4cpio ',
'Sv4crc '=> 'application/x-sv4crc ',
'Tar '=> 'application/x-tar ',
'Tcl '=> 'application/x-tcl ',
'Tex '=> 'application/x-tex ',
'Textinfo' => 'application/x-textinfo ',
'Text' => 'application/x-textinfo ',
'T' => 'application/x-troff ',
'Tr' => 'application/x-troff ',
'Roff' => 'application/x-troff ',
'Man '=> 'application/x-troff-man ',
'Me' => 'application/x-troff-me ',
'Ms' => 'application/x-troff-MS ',
'Ustar' => 'application/x-ustar ',
'Src' => 'application/x-wais-source ',
'Xhtml '=> 'application/xhtml + XML ',
'Xht '=> 'application/xhtml + XML ',
'Zip' => 'application/zip ',
'Au '=> 'audio/basic ',
'Snd' => 'audio/basic ',
'Mid '=> 'audio/midi ',
'Midi '=> 'audio/midi ',
'Kar '=> 'audio/midi ',
'Mpga' => 'audio/mpeg ',
'Mp2' => 'audio/mpeg ',
'Mp3' => 'audio/mpeg ',
'Wma' => 'audio/mpeg ',
'Aif' => 'audio/x-aiff ',
'Aiff '=> 'audio/x-aiff ',
'Aifc '=> 'audio/x-aiff ',
'M3u' => 'audio/x-mpegurl ',
'Ram '=> 'audio/x-pn-realaudio ',
'Rm '=> 'audio/x-pn-realaudio ',
'Rpm '=> 'audio/x-pn-realaudio-plugin ',
'A' => 'audio/x-realaudio ',
'Wav '=> 'audio/x-wav ',
'Pdb' => 'chemical/x-pdb ',
'XYZ' => 'chemical/x-XYZ ',
'Bmp '=> 'image/bmp ',
'Gif' => 'image/GIF ',
'Ief' => 'image/ief ',
'Jpeg '=> 'image/jpeg ',
'Jpg '=> 'image/jpeg ',
'Jpe' => 'image/jpeg ',
'PNG '=> 'image/png ',
'Tiff '=> 'image/tiff ',
'Tif '=> 'image/tiff ',
'Djvu '=> 'image/vnd. djvu ',
'Djv' => 'image/vnd. djvu ',
'Wbmp '=> 'image/vnd. wap. wbmp ',
'Ras '=> 'image/x-cmu-raster ',
'Pnm '=> 'image/x-portable-anymap ',
'Pbm' => 'image/x-portable-bitmap ',
'Pgm '=> 'image/x-portable-graymap ',
'Ppm '=> 'image/x-portable-pixmap ',
'Rgb '=> 'image/x-rgb ',
'Xbm '=> 'image/x-xbitmap ',
'Xpm' => 'image/x-xpixmap ',
'Xwd '=> 'image/x-xwindowdump ',
'Gies' => 'model/iges ',
& Apos; iges & apos; = & apos; model/iges & apos ',
'Msh' => 'model/mesh ',
'Mesh '=> 'model/mesh ',
'Silo' => 'model/mesh ',
'Wrl' => 'model/jpa ',
'Jpa' => 'model/jpa ',
'Css '=> 'text/css ',
'Html' => 'text/html ',
'Htm '=> 'text/html ',
'Asc '=> 'text/plain ',
'Txt '=> 'text/plain ',
'Rtx' => 'text/richtext ',
'Rtf '=> 'text/rtf ',
'Sgml' => 'text/sgml ',
'Sgm' => 'text/sgml ',
'Tsv' => 'text/tab-separated-values ',
'Wml' => 'text/vnd. wap. wml ',
'Wmls' => 'text/vnd. wap. wmlscr limit pt ',
'Etx' => 'text/x-setext ',
'Xsl '=> 'text/XML ',
'Xml' => 'text/XML ',
'MPEG '=> 'video/mpeg ',
'Mpg' => 'video/mpeg ',
'Mpe' => 'video/mpeg ',
'Qt '=> 'video/quicktime ',
'Mov' => 'video/quicktime ',
'Mxu' => 'video/vnd. mpegurl ',
'Av' => 'video/x-msvideo ',
'Movi' => 'video/x-sgi-Movi ',
'Wmv '=> 'application/x-mplayer2 ',
'Ice '=> 'X-conference/x-cooltalk ',
);

Function download ($ filepath = '', $ downname = '')
{
If ($ filepath = ''AND! $ This-> filepath)
{
$ This-> ErrInfo = $ this-> _ LANG ['err']. ':'. $ this-> _ LANG ['args _ empty'];
Return false;
}
If ($ filepath = '') $ filepath = $ this-> filepath;
If (! File_exists ($ filepath ))
{
$ This-> ErrInfo = $ this-> _ LANG ['err']. ':'. $ this-> _ LANG ['File _ not_exists '];
Return false;
}
If ($ downname = ''AND! $ This-> downname) $ downname = $ filepath;
If ($ downname = '') $ downname = $ this-> downname;
// File extension
$ FileExt = substr (strrchr ($ filepath, '.'), 1 );
// File type
$ FileType = $ this-> MIMETypes [$ fileExt]? $ This-> MIMETypes [$ fileExt]: 'application/octet-stream ';
// Whether it is an image
$ IsImage = False;
/*
Brief description: getimagesize (). For details, see the manual.
Description: it is an effective method to determine whether a file is an image. it is often used for file Upload verification.
*/
$ ImgInfo = @ getimagesize ($ filepath );
If ($ imgInfo [2] & $ imgInfo ['bits '])
{
$ FileType = $ imgInfo ['Mime ']; // supports non-standard extensions
$ IsImage = True;
}
// Display mode
If ($ this-> is_attachment)
{
$ Attachment = 'attachment'; // specifies the download dialog box.
}
Else
{
$ Attachment = $ isImage? 'Line': 'attachment ';
}
// Read the file
If (is_readable ($ filepath ))
{
/*
Brief description: ob_end_clean () clears and closes the output buffer. for details, see the manual.
Note: the output buffer is disabled so that the file fragment content is sent out after being read to the memory, reducing resource consumption.
*/
Ob_end_clean ();
/*
HTTP header information: indicates that the client can receive responses with a lifetime not greater than the specified time (second ).
*/
Header ('cache-control: max-age = 000000 ');
/*
HTTP header information: cache file Expiration Time (Greenwich Mean Time)
*/
Header ('expires: '. gmdate ('d, d m y h: I: S', time () + 31536000). 'gmt ');
/*
HTTP header information: The last modification time of the file during the service period
Cache-control, Expires, and Last-Modified all control the browser Cache header information.
In some portals with a large volume of traffic, setting a proper cache can avoid excessive server requests and relieve the pressure on the server to a certain extent.
*/
Header ('last-Modified: '. gmdate ('d, d m y h: I: S', filemtime ($ filepath). 'gmt '));
/*
HTTP header information: The file encoding (Encode) method. because of the diversity of file requests in the attachment, changing the encoding method may damage the file, so it is none.
*/
Header ('content-Encoding: none ');
/*
HTTP header: indicates the file type requested by the browser.
1. if it is always specified as application/octet-stream, it indicates that the file is a binary stream and the download is always prompted.
2. specify the corresponding type. for example, if an mp3 file is requested and the corresponding MIME type is audio/mpeg, IE will automatically start Windows Media Player for playback.
*/
Header ('content-type: '. $ fileType );
/*
HTTP header information: if it is attachment, the browser will be notified that the "file download" dialog box will pop up during access, and the default name of the file to be saved (it can be different from the server file name)
If you want the browser to directly display the content, you must specify the content as inline, slice, and text.
*/
Header ('content-Disposition: '. $ attachment.'; filename = '. $ downname );
/*
HTTP header: tells the browser the file length
(Does IE not have the file size information when downloading files ?)
*/
Header ('content-Length: '. filesize ($ filepath ));
// Open the file (binary read-only mode)
$ Fp = fopen ($ filepath, 'RB ');
// Output file
Fpassthru ($ fp );
// Close the file
Fclose ($ fp );
Return true;
}
Else
{
$ This-> ErrInfo = $ this-> _ LANG ['err']. ':'. $ this-> _ LANG ['File _ not_readable '];
Return false;
}
}
}
?>

The extract () function, readfile (), can be used to download the server source file. next I will introduce you to the method of downloading the readfile...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.