About sending files to clients using PHP - sample code explanation_PHP tutorial

WBOY
Release: 2016-07-13 17:52:19
Original
1287 people have browsed it

[php]
function downloadFile( $fullPath ){

// Must be fresh start
if( headers_sent() ) //check if any header has been sent
Die('Headers Sent'); //Equivalent to exit()

// Required for some browsers
if(ini_get('zlib.output_compression')) //Gets the value of a configuration option
ini_set('zlib.output_compression', 'Off'); //This module allows PHP to transparently read and write gzip (.gz) compressed files

// File Exists?
if( file_exists($fullPath) ){
       
// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);//Return file path information
/*
$path_parts = pathinfo("/www/htdocs/index.html");
echo $path_parts["dirname"] . "n";
echo $path_parts["basename"] . "n";
Echo $path_parts["extension"] . "n";//Suffix name
The information returned is:
/www/htdocs
Index.html
html
*/
$ext = strtolower($path_parts["extension"]); //Convert the string to lowercase
       
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
​​​Default: $ctype="application/force-download"; ​​
}  

header("Pragma: public"); // required indicates that the response can be saved by any cache
/*
The same that "Cache-Control: public"
Public: Indicates that the response can be saved by any cache, even if the response is generally not cacheable or cacheable only in non-shared caches.
Private: Indicates that some or all parts of the response message are intended for one user and must not be saved in the shared cache. You can use the source server
The server can declare that specific parts of the response are specific to a certain user and are invalid for requests from other users. A private
A (non-shared) cache can cache this response.
No-cache: If the no-cache cache control directive does not specify a field-name, then a cache cannot use this response
Subsequent requests will be satisfied only if it is successfully revalidated by the source server. This allows the origin server to prevent ringing
should be cached, even if the cache has been configured to return stale responses to the client.
If the no-cache cache control directive specifies one or more field-names, the cache can use this response to satisfy
Subsequent requests, but this is limited to other restrictions on cache. However, the specified filed-name must not be used later
Sent in response to a request if the response was not successfully revalidated by the origin server. This allows the origin server to prevent
Cache deduplication uses certain header fields in the response, but still allows the cache to save the rest of the response.
/*
The Pragma header specifies directives for proxy and gateway systems.
Since many proxy systems may exist between a client and server, Pragma
headers must pass through each proxy. When the Pragma header reaches
The server, the header may be ignored by the server software.

The only directive defined in HTTP/1.0 is the no-cache directive. It is
used to tell caching proxies to contact the server for the requested
Document, instead of using its local cache. This allows the client to
Request the most up-to-date document from the original web server,
Without receiving a cached copy from an intermediate proxy server.

The Pragma header is an HTTP 1.0 feature, and is maintained in HTTP 1.1
For backward compatibility. No new Pragma directives will be defined in
The future.
*/
header("Expires: 0");
/*
The Expires entity header field (entity-header) gives the time after which the response is considered stale. A stale cache item
                                                                                                                                                                - out out out of the cache (either a proxy cache or a user-agent cache) cannot be returned to the client unless the cached entry is cached by the origin server
Verified by (or by an intermediate cache that holds a fresh copy of the entity).
0 means that it expires immediately, which means not cache.
*/
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
/*
Post-check and pre-check cache control directives must appear together
in pairs other wise they are ignored.
                                              header("Cache-Control: private",false); // required for browser certains
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename="".basename($fullPath)."";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
Ob_clean(); //Clean (erase) the output buffer
Flush(); //Refresh the buffer of the PHP program, regardless of the circumstances under which PHP is executed (CGI, web server, etc.). This function sends all the program's output so far to the user's browser.
Readfile($fullPath); //Read a file and write it to the output buffer.

} else
Die('File Not Found');

}
?>

This is the sample code in the PHP manual. If I can’t understand it, I will translate it one by one.

The following is

© kekehu / Technical Resources / 2009.02.17 / 10:15 / 4246PV

The cache of web pages is controlled by the "Cache-control" in the HTTP message header. Common values ​​include private, no-cache, max-age, must-revalidate, etc. The default is private. Its function is divided into the following situations according to different re-browsing methods:

(1) Open new window

The value is private, no-cache, must-revalidate, then the server will be accessed again when a new window is opened.
And if the max-age value is specified, the server will not be accessed again within this value, for example:
Cache-control: max-age=5 (meaning that when accessing this web page again within 5 seconds, it will not go to the server)

(2) Enter in the address bar
If the value is private or must-revalidate, the server will only be accessed for the first time, and will not be accessed again.
The value is no-cache, then it will be accessed every time.
If the value is max-age, it will not be accessed again before expiration.

(3) Press the back button
If the value is private, must-revalidate, max-age, it will not be revisited,
If the value is no-cache, the access will be repeated every time

(4) Press the refresh button
No matter what the value is,

will be visited repeatedly

When the Cache-control value is "no-cache", accessing this page will not leave a page backup in the Internet temporary article folder.

In addition, caching can also be affected by specifying the "Expires" value. For example, if the Expires value is specified as a time that has long passed, then if you press Enter repeatedly in the address bar when accessing this website, the access will be repeated each time: Expires: Fri, 31 Dec 1999 16:00:00 GMT

For example: disable page caching in IE

http response message header settings:

CacheControl = no-cache
Pragma=no-cache
Expires = -1

Expires is a good thing. If the web pages on the server change frequently, set it to -1 to indicate immediate expiration. If a web page is updated at 1 am every day, you can set Expires to 1 am the next day.

When the HTTP1.1 server specifies CacheControl = no-cache, the browser will not cache the web page.

Legacy HTTP 1.0 servers cannot use the Cache-Control header.
So for backward compatibility with HTTP 1.0 servers, IE provides special support for HTTP using the Pragma:no-cache header.
If the client communicates with the server over a secure connection (https://) and the server returns the Pragma:no-cache header in the response,
then Internet Explorer will not cache this response. Note: Pragma:no-cache only prevents caching when used in a secure connection. If used in a non-secure page, the handling is the same as Expires:-1. The page will be cached but marked as expired immediately.
Author: wolinxuebin

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478109.htmlTechArticle[php] ?php function downloadFile( $fullPath ){ // Must be fresh start if( headers_sent() ) //check if any header has been sent die(Headers Sent); //Equivalent to exit() // Required...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!