Настройка во время выполнения
Поведение этих функций зависит от установок в php.ini.
Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.
There are two main decisions you have to make. First, how much shared memory do you want to set aside for APC, and second, whether you want APC to check if a file has been modified on every request. The two ini directives involved here are apc.shm_size and apc.stat. Read the sections on these two directives carefully below.
Once you have a running server, you should copy the apc.php script that comes with the extension to somewhere in your docroot and load it up in your browser. It provides you with a detailed look at what is happening in your cache. If you have GD enabled in PHP, it will even have pretty graphs. First thing to check is of course that it is actually caching files. Assuming it is working you should then pay close attention to the Cache full count number on the left. That tells you the number of times the cache has filled up and has had to forcefully clean up any entries not accessed within the last apc.ttl seconds. You should configure your cache to minimize this number. If you are constantly filling your cache, the resulting cache churn is going to hurt performance. You should either set more memory aside for APC, or use apc.filters to cache fewer scripts.
Name | Default | Changeable | Changelog |
---|---|---|---|
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12. |
apc.shm_segments | "1" | PHP_INI_SYSTEM | |
apc.shm_size | "30" | PHP_INI_SYSTEM | |
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13. |
apc.num_files_hint | "1000" | PHP_INI_SYSTEM | |
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM | |
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0. |
apc.filters | NULL | PHP_INI_SYSTEM | |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM | |
apc.slam_defense | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6. |
apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7. |
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7. |
apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10. |
apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11. |
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11. |
apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12. |
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13. |
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM | |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM | |
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM | |
apc.localcache | "0" | PHP_INI_SYSTEM | Available since APC 3.0.14. |
apc.localcache.size | "512" | PHP_INI_SYSTEM | Available since APC 3.0.14. |
apc.coredump_unmap | "0" | PHP_INI_SYSTEM | Available since APC 3.0.16. |
Краткое разъяснение конфигурационных директив.
- apc.enabled boolean
-
apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).
- apc.shm_segments integer
-
The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.
- apc.shm_size integer
-
The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
- apc.optimization integer
-
The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
- apc.num_files_hint integer
-
A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.
- apc.user_entries_hint integer
-
Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.
- apc.ttl integer
-
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.
- apc.user_ttl integer
-
The number of seconds a user cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.
- apc.gc_ttl integer
-
The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.
- apc.cache_by_default boolean
-
On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.
- apc.filters string
-
A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.
- apc.mmap_file_mask string
-
If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.
- apc.slam_defense integer
-
On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.
Deprecated by apc.write_lock.
- apc.file_update_protection integer
-
When you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.
- apc.enable_cli integer
-
Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.
- apc.max_file_size integer
-
Prevent files larger than this value from getting cached. Defaults to 1M.
- apc.stat integer
-
Be careful if you change this setting. The default is for this to be On which means that APC will stat (check) the script on each request to see if it has been modified. If it has been modified it will recompile and cache the new version. If you turn this setting off, it will not check. That means that in order to have changes become active you need to restart your web server. On a production server where you rarely change the code, turning stats off can produce a significant performance boost.
For included/required files this option applies as well, but note that if you are using relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.
- apc.write_lock boolean
-
On busy servers when you first start up the server, or when many files are modified, you can end up with all your processes trying to compile and cache the same files. With write_lock enabled, only one process at a time will try to compile an uncached script while the other processes will run uncached instead of sitting around waiting on a lock.
- apc.report_autofilter boolean
-
Logs any scripts that were automatically excluded from being cached due to early/late binding issues.
- apc.include_once_override boolean
-
Optimize include_once() and require_once() calls and avoid the expensive system calls used.
- apc.rfc1867 boolean
-
RFC1867 File Upload Progress hook handler is only available if you compiled APC against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.
Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.
Пример #1 An apc.rfc1867 example
<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>Результатом выполнения данного примера будет что-то подобное:
Array ( [total] => 1142543 [current] => 1142543 [rate] => 1828068.8 [filename] => test [name] => file [temp_filename] => /tmp/php8F [cancel_upload] => 0 [done] => 1 )
- apc.rfc1867_prefix string
-
Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.
- apc.rfc1867_name string
-
Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.
- apc.rfc1867_freq string
-
The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with 'k', 'm', or 'g' for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.
- apc.localcache boolean
-
This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.
- apc.localcache.size integer
-
The size of the local process shadow-cache, should be set to a sufficently large value, approximately half of apc.num_files_hint.
- apc.coredump_unmap boolean
-
Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.
ВниманиеThis feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.
Замечание: Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.
Коментарии
To automatically cache only PHP class files named "<class name>.class.php", add the following lines to php.ini.
apc.cache_by_default = "Off"
apc.filters = "+\.class\.php$"
Notes:
- The regexp is case /sensitive/, so if, say, your project contains filenames with mixed case, you'll need something like "+\.(class|CLASS)\.(php|PHP)$". I've tried delimiting patterns and using the "i" modifier, but that doesn't seem to work.
- Setting cache_by_default to "On" and applying the positive filter will /not/ work.
If you have more complicated requirements and, like me, you're not familiar with POSIX Extended Regular Expressions (ERE) inparticular, you may find the following link useful. http://www.regular-expressions.info/refflavors.html
I'm trying to get upload progress with apc_fetch.
I founded apc_fetch always return false till the upload completed.After fews hours debug, I finally notice that my APC_UPLOAD_PROGRESS was set after the file form.
SO, You should write your form like this
<input type="hidden" id="file_id" name="APC_UPLOAD_PROGRESS" value="blablabla"/>
<input type="file" id="select_file" name="file" value="upload" onchange="parent.test();"/>
the hidden field with name="APC_UPLOAD_PROGRESS" SHOULD be ALWAYS BEFORE input type="file"
The apc.rfc1867 example code above is a little fast and loose for those running in environments where APC RFC1867 may or may not be available. This is a little more expressive:
<?php
// if we have PHP and APC
$havePHP = (1 === version_compare(PHP_VERSION, '5.2.0') ? true : false);
$haveAPC = (extension_loaded('apc') && 1 === version_compare(phpversion('apc'), '3.0.13') ? true : false);
if ($havePHP && $haveAPC) {
// if APC and upload tracking is enabled
if (ini_get('apc.enabled') && ini_get('apc.rfc1867')) {
// get the stats
$key = ini_get('apc.rfc1867_prefix') . $_REQUEST['apcid'];
$stats = apc_fetch($key);
}
}
?>
apc_fetch always returned false. Turns out that "apc.rfc1867" was set to "0". I added this line to my php.ini:
apc.rfc1867 = 1
but it could have certainly been changed with ini_set(). That took me way to long to figure out.
For anyone wondering why shm_segments is being ignored on their setup, it could be because of the following:
If you've configured APC to use memory mapped files (with the --enable-mmap option), the shm_segments setting is ignored unless you specify a file mask via the mmap_file_mask setting.
This is because APC won't attempt to create multiple anonymous files to map into memory without a mask (since it has no way of naming them sensibly). To set up multiple segments you have to give a file mask so they can be named separately.
apc.mmap_file_mask=/tmp/apc.XXXXXX
Make sure to use exactly 6 "X"s (this is the part that is changed by APC). You can place these files anywhere, they don't have to go in /tmp.
With that said, I'm not sure what the performance impact of having multiple MMAP segments would be. I'm guessing it would probably be negative so you probably don't want to do this.
If you are getting 0kb out of 0kb for your upload progress with large files, make sure that upload_max_filesize and post_max_size are larger than the file you are uploading. As far as I can tell, apc.max_file_size does not affect it.
Want to avoid segmentation with apc.shm_segments?If your linux server limits the shared memory block size and you're forced to use apc.shm_segments instead, change the setting by using (here is 512M but change it as you like):
# sysctl -w kernel.shmmax=536870912
(but if you want the change to be permanent after a restart you would have to add the following line in /etc/sysctl.conf
kernel.shmmax=536870912)
and updating apc.ini
apc.shm_segments="1"
apc.shm_size="512"
apc.stat is an extremely important setting for a production server, especially if many files are accessed on every request, which is quite normal on complicated web applications.
Always aspire to use:
apc.stat="0"
so that APC does not try to check that each and every file exists on every request you make. It also means you can update files on your server without crashing incoming requests on that time fragment. Whenever you wish to force APC to re-read all the files, simply clear the cache or restart your server.
apc.stat is an extremely important setting for a production server, especially if many files are accessed on every request, which is quite normal on complicated web applications.
Always aspire to use:
apc.stat="0"
so that APC does not try to check that each and every file exists on every request you make. It also means you can update files on your server without crashing incoming requests on that time fragment. Whenever you wish to force APC to re-read all the files, simply clear the cache or restart your server.
apc.include_once_override=1 can cause more problems than it solves. If you're running into weird errors regarding relative paths, make sure this setting is off. PHP 5.3 already implements most of the speed ups in these calls anyway.
I took some time to look at the preload_path option.
At the moment of writing the preload_path option is broken because of a bug in the APC source code
which will not allow you to properly preload the cache.
The way to fix it :
Inside 'main_apc.c' in the method called 'static int apc_load_data(const char *data_file TSRMLS_DC)', the length of the key of the value that needs to be stored is determined with the following line :
key_len = strlen(key);
If I am correct this is only the length of the string itself without the null-terminator
However, "_apc_store" seems to want the length of the key string including the terminator.
If I change the line above to :
key_len = strlen(key)+1;
then the preload function works as expected.
You can also notice that 1 character is missing when looking at the user cache entries apc.php. But if you try to use that as a key then APC will not return the contents so that didn't work as a workaround.
If one is able to compile the apc library from source, then one can of course easily fix this option by changing the source code.
Files in the specified path should have the extension '.data'.
The filename itself will become the key for the data that is in that specific file.
The data in the file is a serialized string representing what you want to assign to the specific key. For example s:2:"123" will generate the string "123".
One can only specify 1 value for each key and it should be null-terminated.
It is not possible to preload PHP scripts.
Only values that one retrieved with apc_fetch can be preloaded.
Note: If you want to run a script on Windows with apc.enabled=1 as a scheduled task whilst another instance of php is running (like on a webserver) apparently you have to disable apc for this scheduled task, otherwise it will not run and you will have something in your error log like: PHP Fatal error: PHP Startup: apc_shm_create: shmget(0, 33554432, 658) failed: No such file or directory.
So simply execute your scheduled task with:
c:\php\php.exe -d apc.enabled=0 and all will be fine.