Share a super handy PHP header download function

Source: Internet
Author: User
Tags explode header

  This article is mainly for you to share a super good PHP header download function, need friends can refer to the following

The code is as follows: <?php/**  * send file  *  * @author: Legend (legendsky@hotmail.com)  * @link: http://www.ugia.cn/ ? p=109  * @description: Send file to client  * @version: 1.0  *  * @param string   $fileName &nbs P     file name or path  * @param string   $fancyName     Custom file name, NULL to use filename  * @param boolean &N BSP; $forceDownload whether to force download  * @param integer   $speedLimit     speed limit, in bytes, 0 is unrestricted, Windows Server is not supported  * @param string   $ $contentType   file type, default to Application/octet-stream  *  * @return Boolean  */ function SendFile ($fileName, $fancyName = ', $forceDownload = true, $speedLimit = 0, $contentType = ') {    I F (!is_readable ($fileName))     {        header ("http/1.1 404 Not Found");     &N Bsp   return false;    }       $FILESTAT = stat ($fileName);     $lastModified = $fileStat [' Mtime '];   &NBSP   $MD 5 = MD5 ($fileStat [' Mtime ']. " ='. $fileStat [' ino ']. ' ='. $fileStat [' size ']);     $etag = ' "'. $MD 5. '-' . CRC32 ($MD 5). '"';       Header (' last-modified: ' Gmdate ("D, D M Y h:i:s", $lastModified). ' GMT ');     Header ("ETag: $etag");       if (isset ($_server[' http_if_modified_since ']) && strtotime ($_server[' http_if_modified_ SINCE ']) >= $lastModified)     {        Header ("http/1.1 304 not Modified");   &nbs P     return true;    }       if (isset ($_server[' http_if_unmodified_since ')) && strtotime ($_server[' Http_if_unmodified_since '] < $lastModified)     {        http/1.1 header ("304 Not modif IED ");         return true;    }       if (isset ($_server[' Http_if_none_match ')) &&  $_server[' Http_if_none_ MATCH '] = = $etag)     {  &NBsp     Header ("http/1.1 304 not Modified");         return true;    }       if ($fancyName = = ")             $fancyName = Basena Me ($fileName);    }       if ($contentType = = ")     {        $contentType = ' A Pplication/octet-stream ';    }       $fileSize = $fileStat [' Size '];          $contentLength = $fileSize;     $isPartial = false;       if (isset ($_server[' Http_range '))     {        if (Preg_match ('/^byte S= (d*)-(d*) $/', $_server[' Http_range '], $matches))         {                $startPos = $matches [1];             $endPos = $matches [2];               if ($startPos = = ' && $endPos = = ')   &NBSp         {                return false;       & nbsp    }               if ($startPos = = ")           & nbsp {                $startPos = $fileSize-$endPos;         &NB Sp       $endPos = $fileSize-1;                         else if ($endPos = = ")   &NBSP ;         {                $endPos = $fileSize-1;   &nbs P        }               $startPos = $startPos < 0? 0: $startPos;             $endPos = $endPos > $fileSize-1? $fileSize-1: $endPos;               $length = $endPos-$startPos + 1; &nbsP             if ($length < 0)             {    &N Bsp           return false;                           $contentLength = $length;             $isPartial = true;        }     {     //Send headers     if ($isPartial)   &N Bsp {        header (' http/1.1 206 Partial Content ');         header ("Content-range:b Ytes $startPos-$endPos/$fileSize ");      }     Else     {        Header ("http/1.1 OK");   &N Bsp     $startPos = 0;         $endPos = $contentLength-1;    }       header (' Pragma:cache ');     Header (' Cache-control:public, must-revalidate, max-age=0 ');     Header (' accept-ranges:bytes ');     Header (' Content-type: ' $contentType);     Header (' content-length: ' $contentLength);       if ($forceDownload)     {        header (' Content-disposition:attachme nt Filename= "'. Rawurlencode ($fancyName). //Chinese characters automatically convert to URL code   header (' content-disposition:attachment; Filename= "'. $fancyName. '"');    }       header ("content-transfer-encoding:binary");       $bufferSize = 2048;       if ($speedLimit!= 0)     {        $packetTime = Floor ($bufferSize * 1 000000/$speedLimit);    }       $bytesSent = 0;     $FP = fopen ($fileName, "RB");     fseek ($fp, $startPos);      //fpassthru ($FP);       while ($bytesSent < $contentLength &&!feof ($fp) && connection_status () = = 0) &nb Sp   {&nbsP       if ($speedLimit!= 0)                     list ($u SEC, $sec) = Explode ("", Microtime ());              $outputTimeStart = ((float) $usec + (float) $sec);        }           $readBufferSize = $contentLength-$bytesSent < $buffe Rsize? $contentLength-$bytesSent: $bufferSize;         $buffer = Fread ($fp, $readBufferSize);                   $buffer Echo;           Ob_flush ();         flush ();           $bytesSent + + $readBufferSize;           if ($speedLimit!= 0)         {            List ($usec, $sec) = Explode ("", Microtime ());              $OUTPUTTIMEEND = ((f Loat) $usec + (float) $sec);              $useTime = ((float) $outputTimeEnd-(float) $outputTimeStart) * 1000000;             $sleepTime = round ($packetTime-$useTime);             if ($sleepTime > 0)             {                usleep ($sleepTime);                     {   }        &NBSP ;   return true; }  ?>
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.