search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the application of caching technology in PHP_PHP Tutorial

Detailed explanation of the application of caching technology in PHP_PHP Tutorial

Jul 13, 2016 pm 05:29 PM
phpwebapplicationpowerfultechnologyofcacheScriptexplaindesigndetailedlanguage

PHP,一门最近几年兴起的web设计脚本语言,由于它的强大和可伸缩性,近几年来得到长足的发展,php相比传统的asp网站,在速度上有绝对的优势,想mssql转6万条数据php如需要40秒,asp不下2分钟.但是,由于网站的数据越来越多,我们渴求能更快速的调用数据,不必要每次都从数据库掉,我们可以从其他的地方,比方一个文件,或者某个内存地址,这就是php的缓存技术,也就是Cache技术.


一般来说,缓存的目的是把数据放在一个地方让访问的更快点,毫无疑问,内存是最快的,但是,几百M的数据能往内存放么?这不现实,当然,有的时候临时放如服务器缓存,如ob_start()这个缓存页面开启的话在发送文件头之前页面内容都被缓存在内存中,知道等页面输出自动清楚或者等待ob_get_contents的返回,[或者被ob_end_clean显示的清除,这在静态页面的生成中能很好的利用,在模板中能得到很好的体现,我的这篇文章深入的讨论了:

 谈PHP生成静态页面,这是一种方式,但这是临时性的,不是解决我们问题的好方法.

另外,在asp中有一对象application,可以保存公用的参数,这也算点缓存,但在php,我至今没看到开发者产出这种对象,的确,没必要.asp.net的页面缓存技术就用的是viewstate,而cache就是文件关联,(不一定准确),文件被修改,更新缓存,文件没被修改而且不超时(注释1),就读取缓存,返回结果,就是这个思路,看看这个源码:

class cache{
/*
Class Name: cache
Description: control to cache data,$cache_out_time is a array to save cache date time out.
Version: 1.0
Author: Old farmer cjjer
Last modification:2006-2-26
Author URL: http://www.cjjer.com
*/
private $cache_dir;
private $expireTime=180;//The cache time is 60 seconds
function __construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname ,0777)){
                                                                                                                                                                                    ,,,,,,,,,,,;,; ;cache_dir = $cache_dirname;
}
function __destruct(){
echo Cache class bye.;
}

function get_url() {
if (!isset( $_SERVER[REQUEST_URI])) {
                                                                                                               🎜>                                                                                                            _SERVER[QUERY_STRING])) ? ? . $_SERVER[QUERY_STRING] : ;
}

return $url;
}

function warn($errorstring){
echo "An error occurred:
".$errorstring."
";
}

function cache_page($pageurl,$pagedata){
if(!$fso=fopen($pageurl,w)){
$this->warns(Cache file cannot be opened.);// trigger_error
return false;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB, exclusive lock
$this->warns(Cache file cannot be locked.) ;//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize to write other formats
$this-> ;warns(Unable to write to cache file.);//trigger_error
return false;
}
flock($fso,LOCK_UN);//Release lock
fclose($fso);
return true;
}

function display_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn(Cache file cannot be read. );//trigger_error
return false;
}
echo Read cache file:.$cacheFile;
//return unserialize(file_get_contents($cacheFile));
$fso = fopen ($cacheFile, r);
$data = fread($fso, filesize($cacheFile));
fclose($fso);
return $data;
}

function readData($cacheFile=default_cache.txt){
$cacheFile = $this->cache_dir."/".$cacheFile;
if(file_exists($cacheFile)&&filemtime($cacheFile)>( time()-$this->expireTime)){
                                                                                     else{
                $data="from here wo can get it from mysql database,update time is ".date(l dS of F Y h:i:s A).", The expiration time is: ".date(l dS of F Y h:i:s A,time()+$this->expireTime)."----------";
$this ->cache_page($cacheFile,$data);
}
      return $data;
}



}
?>

Below I will interrupt this code to explain it line by line.
Three: Program Dialysis

This cache class (class is nothing good) Scared. Please continue reading) The name is cache and has 2 attributes:

private $cache_dir;
private $expireTime=180;

$cache_dir is the parent directory of the relative website directory where the cache file is placed, $expireTime(Comment One ) is the expiration time of our cached data, mainly based on this idea:
When the data or file is loaded, first determine whether the cache file exists, return false, and the file was last modified Is the sum of time and cache time greater than the current time? If it is greater, it means that the cache has not expired. If it is smaller, it returns false. When false is returned, the original data is read, written to the cache file, and the data is returned. ,

Then look at the program:

function __construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname,0777)){
$this-> ;warn(The cache file does not exist and cannot be created, it needs to be created manually.); >
When the class is instantiated for the first time, a default function is constructed with parameters to cache the file name. If the file does not exist, create a folder with editing permissions. An exception will be thrown when the creation fails. Then $ of the cache class The cache_dir attribute is set to this folder name. All our cache files are in



http://www.bkjia.com/PHPjc/509203.html

www.bkjia.com

true

TechArticlePHP, a web design scripting language that has emerged in recent years, due to its power and scalability, has recently PHP has made great progress in the past few years. Compared with traditional ASP websites, PHP has an absolute advantage in speed. I think...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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

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

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.