search
HomeBackend DevelopmentPHP TutorialDetailed introduction to PHP's APC cache (learning and organization)_PHP tutorial

1. Introduction to APC cache
APC, the full name is Alternative PHP Cache, and the official translation is called "Optional PHP Cache". It provides us with a framework for caching and optimizing PHP's intermediate code. APC's cache is divided into two parts: system cache and user data cache.
System Cache
It means that APC caches the compilation results of the PHP file source code, and then compares the time stamps every time it is called. If not expired, the cached intermediate code is used to run. Default cache
3600s (one hour). But this still wastes a lot of CPU time. Therefore, you can set the system cache in php.ini to never expire (apc.ttl=0). However, if you set it up like this, you need to restart the WEB server after changing the PHP code. Currently, this type of cache is commonly used.
User data cache
The cache is read and written by the user using the apc_store and apc_fetch functions when writing PHP code. If the amount of data is not large, you can give it a try. If the amount of data is large, it would be better to use a more specialized memory caching solution like memcache
Cache key generation rules
Each slot in the APC cache will have a key, and the key is
The apc_cache_key_t structure type, in addition to the key-related attributes, the key is the generation of the h field. The h field determines where in the slots array this element falls. The generation rules are different for user cache and system cache. The user cache generates keys through the apc_cache_make_user_key function. The key string passed in by the user relies on the hash function in the PHP kernel (the hash function used by PHP's hashtable: zend_inline_hash_func) to generate the h value.
The system cache generates keys through the apc_cache_make_file_key function. Different solutions can be treated differently through the switch of the APC configuration item apc.stat. In the case of open, i.e.
When apc.stat= On, the compiled content will be automatically recompiled and cached if updated. The h value at this time is the value obtained by adding the device and inode of the file. In the case of shutdown, that is, when apc.stat=off, when the file is modified, if you want the updated content to take effect, you must restart the web server. At this time, the h value is generated based on the path address of the file, and the path here is an absolute path. Even if you use a relative path, the PG (include_path) location file will be searched to obtain the absolute path, so using an absolute path will skip the check and improve the efficiency of the code.
Add caching process
Taking the user cache as an example, the apc_add function is used to add content to the APC cache. If the key parameter is a string, APC will generate the key based on the string. If the key parameter is an array, APC will traverse the entire array and generate the key. Based on these keys, APC will call _apc_store to store the value in the cache. Since this is a user cache, the cache currently used is apc_user_cache. It is the apc_cache_make_user_entry function that performs the write operation, which ultimately calls apc_cache_user_insert to perform the traversal query and write operation. Correspondingly, the system cache uses apc_cache_insert to perform write operations, which will eventually call _apc_cache_insert.
Whether it is user cache or system cache, the general execution process is similar. The steps are as follows:

Locate the position of the current key in the slots array through the remainder operation: cache->slots[key.h % cache->num_slots];
After locating the position in the slots array, traverse the slot linked list corresponding to the current key. If there is a slot key that matches the key to be written or the slot expires, clear the current slot.
Insert a new slot after the last slot.
2. APC module installation
WINDOWS
Step 1: Download php_apc.dll at http://pecl.php.net/package/apc. To match the PHP version, put php_apc.dll into your ext directory

Step 2: Let php.ini support the apc extension module. Then open php.ini and add:

extension=php_apc.dll

apc.rfc1867 = on

apc.max_file_size = 100M

upload_max_filesize = 100M

post_max_size = 100M

//The above parameters can be defined by yourself

Step 3: Check whether PHP APC is supported apc_store apc_fetch PHP APC configuration parameters Explain the related configurations together.

apc.enabled=1 The default value of apc.enabled is 1, you can set it to 0 to disable APC. If you set it to 0, also comment out extension=apc.so (this can save memory resources). Once the APC function is enabled, Opcodes will be cached in shared memory.

apc.shm_segments = 1

Summary 1. Using the Spinlocks lock mechanism can achieve the best performance.

2. APC provides apc.php for monitoring and managing APC cache. Don’t forget to change the administrator name and password

3. APC creates shared memory through mmap anonymous mapping by default, and cache objects are stored in this "large" memory space. The shared memory is managed by APC itself

4. We need to adjust the values ​​of apc.shm_size, apc.num_files_hints and apc.user_entries_hint through statistics. Until the best

5, OK, I admit that apc.stat = 0 can get better performance. I can accept whatever you want.

6, PHP predefined constants, you can use the apc_define_constants() function. However, according to APC developers, pecl hidef has better performance. Just throw out define, which is inefficient.

7. Function apc_store(). For PHP variables such as system settings, the life cycle is the entire application (from the httpd daemon until the httpd daemon is closed). It is better to use APC than Memcached. After all, do not use the network transmission protocol tcp.

8. APC is not suitable for caching frequently changed user data through the function apc_store(), and some strange phenomena will occur.

LIUNX
wget http://pecl.php.net/get/APC-3.1.8.tgz

tar -zxvf APC-3.1.8.tgz cd APC-3.1.8

/usr/local/php/bin/phpize

./configure --enable-apc --enable-mmap --enable-apc-spinlocks --disable-apc-pthreadmutex --with-php-config=/usr/local/php/bin/php-config

make

sudo make install

Add in /usr/local/php/etc/php.ini

extension = "apc.so" ;

;APC setting

apc.enabled = 1

apc.shm_segments = 1

apc.shm_size = 64M

apc.optimization = 1

apc.num_files_hint = 0

apc.ttl = 0

apc.gc_ttl = 3600

apc.cache_by_default = on

Restart apache or /usr/local/php/sbin/php-fpm restart

View phpinfo apc

The following references the APC cache class of the www.initphp.com framework
APC cache class of initphp framework
[php]
if (!defined('IS_INITPHP')) exit('Access Denied!');
/***************************************************** *******************************
* InitPHP 2.0 domestic PHP development framework Dao-APC cache is not suitable for frequently written cache data
*------------------------------------------------ ----------------------------------
* Copyright: CopyRight By initphp.com
* You can use this source code freely, but please keep the author information during use. Respecting the fruits of others’ labor means respecting yourself
*------------------------------------------------ ----------------------------------
* $Author:zhuli
* $Dtime:2011-10-09
*************************************************** **********************************/
class apcInit {
       
/**
* Apc cache-set cache
* * Set cache key, value and cache time
* @param string $key KEY value
* @param string $value value
* @param string $time Cache time
​​*/
Public function set_cache($key, $value, $time = 0) {
If ($time == 0) $time = null; //Permanent cache in case of null
          return apc_store($key, $value, $time);;
}  
       
       
/**
* Apc cache-get cache
* Get cache data through KEY
* @param string $key KEY value
​​*/
Public function get_cache($key) {
         return apc_fetch($key);
}  
       
/**
* Apc cache - clear a cache
* Delete a cache from memcache
* @param string $key KEY value
​​*/
Public function clear($key) {
          return apc_delete($key);
}  
       
/**
* Apc cache-clear all caches
* It is not recommended to use this function
* @return
​​*/
Public function clear_all() {
apc_clear_cache('user'); //Clear user cache
          return apc_clear_cache(); //Clear cache
}  
       
/**
* Check if APC cache exists
* @param string $key KEY value
​​*/
Public function exists($key) {
         return apc_exists($key);
}  
       
/**
* Field increment - used for counting
* @param string $key KEY value
* @param int $step New step value
​​*/
Public function inc($key, $step) {
          return apc_inc($key, (int) $step);
}  
       
/**
* Field decrement - used for counting
* @param string $key KEY value
* @param int $step New step value
​​*/
Public function dec($key, $step) {
          return apc_dec($key, (int) $step);
}  
       
/**
* Return APC cache information
​​*/
Public function info() {
         return apc_cache_info();
}  
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477944.htmlTechArticle1. Introduction to APC Cache APC, the full name is Alternative PHP Cache, and the official translation is called Alternative PHP Cache. It provides us with a framework for caching and optimizing PHP's intermediate code. APC's cache is divided into two parts...
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.