목차
Get a handle on PHP Handlers,handlehandlers
Handlers
CGI – mod_cgi
suPHP – mod_suphp
DSO – mod_php
FastCGI – mod_fcgid
FPM (FastCGI Process Manager) – php-fpm
Web Servers
Apache
Nginx
Conclusion
백엔드 개발 PHP 튜토리얼 Get a handle on PHP Handlers,handlehandlers_PHP教程

Get a handle on PHP Handlers,handlehandlers_PHP教程

Jul 12, 2016 am 09:06 AM

Get a handle on PHP Handlers,handlehandlers

PHP Handlers? mod_php? FPM? How do we make sense of the inner workings of PHP outside of our lines of code? We know we can run PHP on the server to build web applications swiftly, but how can we optimize our environment and configurations to reach maximum scale? We know that PHP has its drawbacks for not being asynchronous or event-driven, which is all the more reason to ensure maximum optimization. The impact of your server environment on your PHP application performance can be more than you think you can afford. A careful examination of your PHP ecosystem will help you avoid suffering performance loss in areas you can otherwise solve for easily.

You can deploy PHP, as an ecosystem, in a myriad of settings. As the demands for web application performance and scalability have increased over time, so have the way in which PHP code is invoked, interpreted and handled. This evolution of configuration optimizations  allows for greater scale, security, and durability. If you are uncertain about how your environment is setup, it may be time to audit your environment and reconsider old architectural decisions. Optimizing your PHP application for speed and reliability extends beyond just your code; taking advantage of the latest technology in PHP handling may solve many of your pain points that you might have been oblivious to subsisting. We’ll explore the various ways in which PHP can be configured to work with your web server and compare these runtimes from a performance and scalability perspective.

Handlers

Under-the-Hood in every PHP application exists a web server and the PHP interpreter. As HTTP traffic comes in, your web server completes the request by providing either the static data (e.g. images, Javascript, CSS) or dynamic data. The web server will pass the request on to PHP to handle the interpretation of your application code, create the response, and hand it back to the web server, to then deliver it back to the customer. During this process, the interface in which the web server communicates with the PHP runtime is called the PHP Handler.

An easy way to check what handler you are running is to create a dummy file on your server named phpinfo.php and place in the following code:

<?php phpinfo(); ?><br>

Load that page up in your browser and look for the Server API entry block.

CGI – mod_cgi

mod_cgi  is a common option even to this day, mainly in shared hosting environments or (extremely) legacy applications that haven’t upgraded in almost a decade. It is old, outdated, and recommended never to use in any modern PHP environment.

Running PHP code using this method creates a new CGI process outside of the Apache process causing the PHP interpreter to load (and configs read) upon every request.  This approach is not necessarily the most efficient nor effective.  Arguably, this method is more secure: using suEXEC mod_cgi can keep the execution of PHP code outside of the scope of Apache meaning that faulty or malicious code cannot go outside of the scope of interpretation. This method is popular for shared hosting environments under the same PHP interpreter roof.

Unfortunately, the bad outweighs the good with this method; because of its inefficient, poor performance, and heavy taxation on server resources, it quickly fell out of preference for serious PHP developers. It also does not support PHP Opcode Cache methods, which clearly rules it out for serious high-traffic environments.

suPHP – mod_suphp

Similar to CGI, suPHP (Single User PHP) is an Apache module. You have the advantage of seeing which user is running which process and taxing the CPU. However, similar to CGI, this is inefficient and as your traffic begins to increase you will very quickly push your server to its limits. The benefit of suPHP is essentially the security and is a popular option for hosting multiple PHP applications on a single server because your PHP scripts run as the owning user. Thus, if your application provides an upload form, the uploaded files will be owned by the same owner of the PHP script itself with the necessary permissions intact. This also guarantees no PHP script execution by any user other than the owner.

With suPHP, you will run PHP as a separate process for each request and quickly max out your resources as your traffic begins to spike. Similar to CGI, mod_suphp quickly fell out of favor for high-traffic scenarios. Unfortunately, suPHP soon fell from popularity as it also provided no support for Opcode Cache. Also, considering its last release was in 2013, it might be safe to assume this project no longer supported.

DSO – mod_php

Considered the de facto standard of PHP handlers, mod_php quickly rose to popularity for its speed and scale. You may probably already have mod_php installed; your phpinfo() dump will show Apache 2.0 Handler under the Server API block.

The DSO handler is perhaps one of the oldest and fastest handlers available. The mod_php module integrates PHP as a part of the Apache process itself allowing Apache to interpret the PHP code. Thus, you do not spawn a new PHP process per request, and your overhead is low as PHP preloads as an Apache child process.

One of the greatest advantages of mod_php is that you can now leverage an Opcode cache (e.g. APC), which in turn, will speed up your average response time in extremely significant orders of magnitude. Speaking of APC, if you have not already checked it out, I have another post in which I briefly cover Opcode Cache, and my colleague Rob Bolton has an excellent article covering it in depth.

A disadvantage to mod_php is that all your PHP application files will be owned and executed by the Apache user. This will cause some loss in visibility into which specific users may be impacting server resources. I do not think for the modern PHP application this is a serious issue; you are probably not running multiple websites on a single server but rather powering one giant PHP application across a farm of servers.

FastCGI – mod_fcgid

FastCGI is what its name implies: a fast PHP implementation handler as a CGI module built with performance in mind. FastCGI will not limit you to only one web server (unlike mod_php) and reduces CPU overhead by keeping PHP scripts in memory and not having to invoke a new PHP process on each request. Security is also tight as you have the benefit of executing PHP scripts as the owning user and not as the Apache user.

A major disadvantage to FastCGI is that it is taxing on your memory consumption (although less so than mod_php). By keeping your PHP scripts in memory, you may find that your RAM usage on your server begins to spike. This is a common symptom with in-memory cache mechanisms, including APC and Memcached. However, you’ll need to find the right tradeoff because keeping data in memory also means lowered CPU usage and faster access to that data, thus reducing the overall response time of your requests.

FastCGI is a good modern alternative to suPHP if security is your primary concern within a shared environment without sacrificing speed.

FPM (FastCGI Process Manager) – php-fpm

While technically not a handler per se, php-fpm is coupled with FastCGI for more efficient process management and can used on any server that is also compatible with FastCGI. FPM (FastCGI Process Manager) is a fitting replacement for those of you who may have had experience with spawn-fcgi to handle worker FastCGI processes. FPM manages the FastCGI SAPI, which is the Server API (the interface between PHP and Apache). As a side note, for command line execution, PHP-CLI is the SAPI for PHP.

FPM also supports opcode cache and allows for sharing your APC cache among all php-fpm workers. The additional features that php-fpm provides enables high-traffic PHP environments to begin to scale at levels never before imagined. These types of technical advantages allowed for more scale, better utilization of hardware and OS resources, smarter process management, and more concurrency and throughput. PHP applications are also able to scale across multiple servers better. As of PHP 5.3.3, FPM now ships with PHP.

Web Servers

We’ve been talking a lot about handlers, but to reach an optimal environment you need to combine it with the right web server for the level of scale you are trying to achieve with your PHP application. The two most popular web servers for PHP applications are Apache and Nginx. While each server operates under their unique technology and has their strengths and weaknesses, Nginx + php-fpm has become a clear contender in the fight for speed and scale.

Apache

Being the most common web server in the world, Apache also has its limitations. As user traffic comes in, Apache will spawn a new worker process per request. Both prefork and MPM mode create new processes per client connection, although worker mode can handle more requests while it serves more than one connection per process. Nevertheless, as your traffic begins to increase you’ll notice your memory begin to exhaust as connections utilize RAM and compete for CPU. You’ll find yourself easily maxing out your connection pool if you run a heavy-traffic environment. You can configure Apache to optimize the number of maximum processes and concurrent connections given your hardware resources, but you’ll still find processes competing, and as traffic increases so do your need to scale.

Nginx

Nginx contains an event-driven, non-blocking, and asynchronous architectural model. If Node.js has taught us anything, this design creates the perfect environment conducive to serving multiple requests at the same time. Because it is non-blocking, it can continue to serve additional events (user connections) without having to wait, and because it is asynchronous, it can handle multiple concurrent users at the same time. The beauty of this model has quickly proven Nginx to be the leading contender for handling massive amounts of traffic under the same server setup. With Nginx, you can even cluster your processes to spawn an additional process per core on your machine, thus increasing your ability to handle more requests per server.

Conclusion

Clearly, you have options. Regardless of whether your primary concern is security or speed, you’ll need to consider your architecture deeply before going down the path of building an ecosystem in which to deploy your PHP application. Take into consideration not only your immediate needs but also your future needs in order to remain scalable as your application grows in size and traffic.

In high traffic environments, coupling the event-driven architectural model of Nginx with php-fpm, you’ll be running PHP optimized to handle massive amounts of traffic. There are, of course, further methods of optimizing the code itself to decrease your average response time, but from a hosting perspective you’ll be rest-assured in flying-high with Nginx and php-fpm under your belt.

原文:https://blog.appdynamics.com/php/get-handle-php-handlers

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1066212.htmlTechArticleGet a handle on PHP Handlers,handlehandlers PHP Handlers? mod_php? FPM? How do we make sense of the inner workings of PHP outside of our lines of code? We know we can run PHP on...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP 로깅 : PHP 로그 분석을위한 모범 사례 PHP 로깅 : PHP 로그 분석을위한 모범 사례 Mar 10, 2025 pm 02:32 PM

PHP 로깅은 웹 애플리케이션을 모니터링하고 디버깅하고 중요한 이벤트, 오류 및 런타임 동작을 캡처하는 데 필수적입니다. 시스템 성능에 대한 귀중한 통찰력을 제공하고 문제를 식별하며 더 빠른 문제 해결을 지원합니다.

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

PHP에서 늦은 정적 결합의 개념을 설명하십시오. PHP에서 늦은 정적 결합의 개념을 설명하십시오. Mar 21, 2025 pm 01:33 PM

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. 프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. Mar 28, 2025 pm 05:12 PM

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

See all articles