


About sending files to clients using PHP - sample code explanation_PHP tutorial
[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');
}
?>
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,
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

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.