Home  >  Article  >  Backend Development  >  PHP details ways to improve concurrency capabilities

PHP details ways to improve concurrency capabilities

WBOY
WBOYforward
2022-08-18 18:00:011484browse

This article brings you relevant knowledge about PHP. It mainly introduces the solutions for improving PHP’s concurrency capabilities. The article introduces it in detail through example code, which is very useful for everyone’s study or work. It has certain reference and learning value. Let’s take a look at it together. I hope it will be helpful to everyone.

(Recommended tutorial: PHP video tutorial)

This article has included programming study notes gitee. Covers PHP, JavaScript, Linux, Golang, MySQL, Redis, open source tools, etc.

PHP used in production environments needs to be optimized to allow PHP itself to perform better. In addition to writing PHP code, php-fpm and php.ini tuning must also be configured. This article explains the configuration tuning of php.ini from the aspects of memory, OPcache, upload, session and security.

Compared with other compiled languages, the biggest disadvantage of PHP is that each request requires some module parsing, and what is actually executed is the work process. Starting the work process requires more resources. At the same time, every request will re-parse some codes, resulting in repeated parsing.

For the optimization of PHP, you can focus on this aspect to consider optimization.

Memory optimization

When running PHP, you need to care about how much memory each PHP process uses. The memory_limit setting in php.ini is used to set how much memory a single PHP process can use. The maximum amount of system memory.

The default value of this setting is 128M, which may be suitable for most small and medium-sized PHP applications. However, if you are running a micro-PHP application, you can lower this value to save system resources. On the contrary, if If you are running a memory-intensive PHP application, you can increase this value. The size of this value is determined by the available system memory. Determining how much value to allocate to PHP is an art. When deciding how much memory to allocate to PHP and how many PHP-FPM processes it can afford, it can be judged based on the following dimensional information:

  • How much memory can be allocated to PHP? Take a VPS with 2G memory as an example. This device may also run other processes, such as MySQL, Nginx, etc., so it is appropriate to leave 512M for PHP.
  • How much memory does each PHP process consume on average? To monitor the memory usage of the process, you can use the command line command top, or you can call the memory_get_peak_usage() function in a PHP script. No matter which method is used, it must be used multiple times. Run the same script and take the average memory consumption.
  • How many PHP-FPM processes can you afford? Suppose I allocate 512M memory to PHP and each PHP process consumes an average of 15M memory, then I can afford 34 PHP-FPM processes.

Are there enough system resources? Finally, you need to confirm that there are enough system resources to run the PHP application and handle the expected traffic. For specific PHP configuration information, please refer to the php-fpm.config configuration file.

; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d( ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0

; The maximum number of processes FPM will fork. This has been designed to control
; the global number of processes when using dynamic PM within a lot of pools.
; Use it with caution.
; Note: A value of 0 indicates no limit
; Default Value: 0
; process.max = 128

; Specify the nice(2) priority to apply to the master process (only if set)
; The value can vary from -19 (highest priority) to 20 (lowest priority )
; Note: - It will only work if the FPM master process is launched as root
; - The pool process will inherit the master process priority
; unless specified otherwise
; Default Value: no set
; process.priority = -19

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
daemonize = no

php-fpm has three operating modes, namely fixed number of processes, number of on-demand processes, and fully dynamic number of processes.

  • The number of processes on demand, a few processes are initialized by default. If the amount is too large, some new processes will be dynamically created. After the request is completed, the newly created processes will be destroyed.
  • Fix the number of processes. By default, a few processes are fixed. If the number of processes is not enough, new requests are waiting and will not be processed until other processes have finished processing.
  • The number of completely dynamic processes means that it is completely controlled by the amount of requests. A process is created for each request and is destroyed after processing.

Turn on Zend OPcache performance acceleration

After determining how much memory to allocate, you can configure PHP’s Zend OPcache extension. OPcache mainly parses some codes into bytecode, so there is no need to repeatedly parse and compile this part of the code in subsequent requests. Reducing the compilation and parsing process can also improve PHP's processing speed.

PHP5.5.0 has this extension built-in. Here are some necessary configuration information:

opcache.memory_consumption = 64: The memory allocated for the opcode cache (unit is MB) , the amount of allocated memory should be able to store the opcodes compiled by all PHP scripts in the application. This value can be set to different sizes according to the size of the application.

opcache.interned_strings_buffer = 16: The amount of memory used to store resident strings (unit is MB). What is a resident string? Behind the scenes, the PHP interpreter will find multiple instances of the same string and save the string in memory. If the same string is used again, the PHP interpreter will use a pointer. The purpose of this is to save memory. By default, PHP resident strings will be isolated in each PHP process. This setting allows the PHP-FPM process pool to store all process-resident strings in a shared buffer so that they can be processed in the PHP-FPM process pool. Resident strings are referenced between multiple processes, which saves more memory.

opcache.max_accelerated_files = 4000: The maximum number of PHP scripts that can be stored in the opcode cache. The range of this value is between 2000 and 100000. This value must be larger than that in PHP applications. The number of files is large.

opcache.validate_timestamps = 1: When the value of this setting is 1, PHP will check whether the content of the PHP script has changed after a period of time. The checking time interval is set by opcache.revalidate_freq specified. If the value of this setting is 0, PHP will not check whether the content of the PHP script has changed, and we must clear the cached opcodes ourselves. It is recommended to set it to 1 in the development environment and 0 in the production environment.

opcache.revalidate_freq = 0: Set how often (in seconds) to check whether the content of the PHP script has changed. The meaning of setting to 0 seconds is that the PHP file will be re-validated on every request only if opcache.validate_timestamps is set to 1, so in the development environment the PHP file will be re-validated every time, but not in the production environment verify.

opcache.fast_shutdown = 1: This setting allows the opcode to use a faster shutdown step, leaving object destruction and memory release to Zend Engine's memory manager.

File upload

If your application allows file upload, it is best to set the maximum file size that can be uploaded. In addition, it is best to set the maximum number of files that can be uploaded at the same time:

file_uploads = 1
upload_max_filesize = 10M
max_file_uploads = 3

By default, PHP allows 20 files to be uploaded in a single request, and the maximum uploaded file is 2MB. Here I It is set so that a maximum of 3 files can be uploaded in a single request, and the maximum size of each file is 10MB. Do not set this value too large, otherwise a timeout will occur.

Note: If you have to upload large files, the configuration of the Web server must be adjusted accordingly. In addition to setting it in php.ini, also adjust the client_max_body_size setting in the Nginx virtual host configuration.

In addition, if you are uploading extra large files, I recommend using Webuploader’s specialized upload component. The front-end slices the large files, and the back-end PHP merges the sliced ​​data to restore the files. For information about the WebUploader application, please refer to the article on this site: Powerful file upload component-WebUploader.

Execution time

max_execution_time is used to set the maximum time a single PHP process can run before terminating. This setting defaults to 30 seconds, and it is recommended to set it to 5 seconds:

max_execution_time = 5

You can call the set_limit_time() function in a PHP script to override this setting.

Suppose we want to generate a report and make the results into a PDF file. This task may take 10 minutes to complete, and we definitely don't want to make the PHP request wait for 10 minutes. We should write a separate PHP file, Let it execute in a separate background process, and it only takes a few milliseconds for the web application to spawn a separate background process and return an HTTP response.

Actually, when we run tasks that take a lot of time to complete, we generally use background processes. For example, we can use PHP's swoole extension to generate reports and send emails in batches, which are time-consuming tasks.

Processing sessions

The default situation of PHP is to store the information generated by the session in the disk, such as the so-called session information. When creating and reading a session, I/O operations are performed on the disk. Reading and writing the disk is actually a relatively time-consuming operation. And session is not convenient for processing the session mechanism of distributed applications. It is recommended to place it in an in-memory service such as Redis and memcached, which has fast read and write speeds and can be processed by a distributed session mechanism.

The following example stores information such as session in memcached memory.

session.save_handler = "memcached"
session.save_path = "服务地址:端口号"

Buffer

The network will be more efficient if more data is sent in fewer chunks instead of less data in more chunks. That is, delivering content to the visitor's browser in fewer fragments reduces the total number of HTTP requests.

Therefore, we need to let PHP buffer the output. By default, PHP has enabled the output buffering function. PHP buffers 4096 bytes of output before sending the content to the Web server. The recommended configuration is as follows:

output_buffering = 4096
implicit_flush = false

如果想要修改输出缓冲区的大小,确保使用的值是4(32位系统)或8(64位系统)的倍数。

安全设置

open_basedir:使用open_basedir选项能够控制PHP脚本只能访问指定的目录,这样能够避免PHP脚本访问不应该访问的文件,一定程度上限制了phpshell的危害。我们一般可以设置为只能访问网站目录:

open_basedir = /data/www

disable_functions:一般我们要禁止系统函数和禁止任何文件和目录的操作,如:

disable_functions = '.....'

expose_php = Off:将此项设置为false即不会再header头输出PHP版本信息。

display_errors = Off:生产环境中,我们应该禁止错误提示,如果是本地开发环境,可以设置为On。

log_errors = On:建议在关闭display_errors后能够把错误信息记录下来,便于查找服务器运行的原因。

error_log:设置PHP错误日志存放的目录。

(推荐教程:PHP视频教程

The above is the detailed content of PHP details ways to improve concurrency capabilities. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete