PHP get local PC files after download Save as _php tutorial

Source: Internet
Author: User
Download the file in PHP we use the most is directly using the ReadFile () function, ReadFile () can implement the server source files to download, let me introduce ReadFile download file methods and performance introduction

Example 1

The code is as follows Copy Code

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");

PDF Source in Original.pdf
ReadFile ("ptindex_user_profilebasc.html");

?>

Example 2

code as follows copy code
< p>

$item =trim ($_get[' fileName '). ". TXT ";
$abs _item= '/usr/home/folder name/folder name/folder name/'. $item;
$browser = ' IE ';
Header (' Content-type: '). ( ($browser = = ' IE ' | | $browser = = ' OPERA ')?
' application/octetstream ': ' 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);

The above can only download local functions, if you want to download the remote we can do the following PHP remote download files to local functions

The code is as follows Copy Code

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 share a class function that supports multiple file downloads

The code is as follows Copy Code

/**
* How to use:
* 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 is wrong. ',
' file_not_exists ' \ = ' file does not exist! ',
' file_not_readable ' = ' file is unreadable! ',
);
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īpt ',
' EPS ' = ' application/postscrīpt ',
' ps ' = ' application/postscrīpt ',
' SMI ' = ' application/smil ',
' Smil ' = ' application/smil ',
' MIF ' = ' application/vnd.mif ',
' 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Ī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-director ',
' dir ' = ' application/x-director ',
' DXR ' = ' application/x-director ',
' DVI ' = ' application/x-dvi ',
' SPL ' = ' application/x-futuresplash ',
' Gtar ' = ' Application/x-gtar ',
' HDF ' = ' APPLICATION/X-HDF ',
' js ' = ' application/x-javascrī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 ',
' Texinfo ' = ' application/x-texinfo ',
' Texi ' = ' application/x-texinfo ',
' 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 ',
' ra ' = ' 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 ',
' IGs ' = ' model/iges ',
' IGEs ' = ' model/iges ',
' MSH ' = ' Model/mesh ',
' Mesh ' = ' model/mesh ',
' Silo ' = ' model/mesh ',
' WRL ' = ' model/vrml ',
' VRML ' = ' model/vrml ',
' 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ī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 ',
' avi ' = ' video/x-msvideo ',
' Movie ' = ' Video/x-sgi-movie ',
' 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 name extension
$FILEEXT = substr (STRRCHR ($filepath, '. '), 1);
File type
$fileType = $this->mimetypes[$fileExt]? $this->mimetypes[$fileExt]: ' Application/octet-stream ';
Whether it is a picture
$isImage = False;
/*
Description: getimagesize (), see Manual
Description: Determine whether a file is an effective means of a picture, commonly used in file upload verification
*/
$imgInfo = @getimagesize ($filepath);
if ($imgInfo [2] && $imgInfo [' bits '])
{
$fileType = $imgInfo [' MIME ']; Support for non-standard extensions
$isImage = True;
}
Display mode
if ($this->is_attachment)
{
$attachment = ' attachment '; Specify the pop-up download dialog box
}
Else
{
$attachment = $isImage? ' Inline ': ' Attachment ';
}
Read file
if (is_readable ($filepath))
{
/*
Description: Ob_end_clean () clear and close the output buffer, see manual
Note: Turn off output buffering so that the content of the file fragment is sent out after it is read into memory, reducing resource consumption
*/
Ob_end_clean ();
/*
HTTP header information: Indicates that the client can receive a response that is not longer than the specified time (in seconds)
*/
Header (' cache-control:max-age=31536000 ');
/*
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 time at which the file was last modified at the end of the service period
Cache-control,expires,last-modified is the header information that controls the browser cache
In some of the large access to the portal, reasonable settings cache to avoid excessive server requests, to some extent, alleviate the pressure of the server
*/
Header (' last-modified: '. Gmdate (' d, D M Y h:i:s ', Filemtime ($filepath). ' GMT '));
/*
HTTP header information: Document encoding (Encode) method, because the file of the attachment request diversification, change the encoding method may corrupt the file, therefore is None
*/
Header (' Content-encoding:none ');
/*
HTTP header information: tells the browser which file type is currently requested.
1. Always specify as Application/octet-stream, which means that the file is a binary stream and always prompts for download.
2. Specify the corresponding type, such as the requested MP3 file, the corresponding MIME type is audio/mpeg, IE will automatically start Windows Media player to play.
*/
Header (' Content-type: '. $fileType);
/*
HTTP header information: If attachment, tells the browser to pop up the file Download dialog box when it is accessed and specify the default name of the file when it is saved (can be different from the server's file name)
If you want the browser to display the content directly, specify as inline, slice, text
*/
Header (' content-disposition: '. $attachment. '; Filename= '. $downname);
/*
HTTP header information: Tell browser file length
(ie download files when the file size information is not?)
*/
Header (' Content-length: '. FileSize ($filepath));
Open file (binary read-only mode)
$fp = fopen ($filepath, ' RB ');
Output file
Fpassthru ($FP);
Close File
Fclose ($FP);
return true;
}
Else
{
$this->errinfo = $this->_lang[' err '). ':' . $this->_lang[' file_not_readable '];
return false;
}
}
}
?>

http://www.bkjia.com/PHPjc/631556.html www.bkjia.com true http://www.bkjia.com/PHPjc/631556.html techarticle Download the file in PHP we use the most is the direct use of the ReadFile () function, ReadFile () can be implemented to the server source files to download, let me introduce to you readfile download the file of the party ...

  • 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.