search
HomeBackend DevelopmentPHP TutorialHow PHP handles the web request process

How PHP handles the web request process

Mar 27, 2018 pm 01:54 PM
phpwebprocess

Many development frameworks have emerged in the PHP world, such as Laravel, ThinkPHP, etc., but regardless of the overall framework, their modes of processing Web requests are the same. This article first explains the basic architecture of PHP development of Web applications, and then respectively Analyze the processing flow of Laravel and ThinkPHP when processing web requests.

Basic architecture of PHP development of Web applications

When PHP develops Web applications, all requests need to point to specific entry files. WebServer is a content distributor. After it accepts the user's request, if the request is for static files such as css, js, etc., WebServer will find the file and then send it to the browser; if the request is /index.php, according to the configuration file , WebServer knows that this is not a static file and needs to find a PHP parser to process it, then it will simply process the request and hand it over to the PHP parser.

WebServer will send the requested Url, data, Http Header and other information to the PHP parser according to the CGI protocol. Next, the PHP parser will parse the php.ini file, initialize the execution environment, and then process the request. Return the processed results in the format specified by CGI and exit the process. The web server then returns the results to the browser. The entire processing process is shown in the figure above.

FastCGI

The PHP parser here is a program that implements the CGI protocol. Every time a request comes, it will parse the php.ini file and initialize the execution environment. This will lead to the performance of the PHP parser. Low, so an improved and upgraded version of CGI, FastCGI, appeared. FastCGI is a language-independent protocol used to communicate between programs (such as PHP, Python, Java) and Web servers (Apache2, Nginx). In theory, programs written in any language can provide Web services through FastCGI. Its characteristic is that it dynamically allocates processing processes to requests to improve efficiency. Most FastCGI implementations maintain a process pool. FastCGI will first start a master process, parse the configuration file, initialize the execution environment, and then start multiple worker processes. When a request comes, the master process passes the request to a worker process and then immediately accepts the next request. And when there are not enough worker processes, the master can pre-start several worker processes according to the configuration and wait; of course, when there are too many idle worker processes, they will be automatically shut down, thus improving performance and saving system resources. Throughout the process, FastCGI plays the role of managing the CGI process.

PHP-FPM

PHP-FPM is a program that implements the FastCGI protocol specifically for PHP. It is actually a PHP FastCGI process manager, responsible for managing a process pool and calling PHP parsing server to handle requests from the web server. PHP-FPM can smoothly transition changes to the php.ini file.

Create a new helloworld.php file and write the following code

   
<?php
  echo"helloworld,";    
  echo"this
 is my first php script.";
  echophpinfo();
?>

After configuring the PHP running environment such as WebServer and PHP-FPM, you can get the output directly by accessing the file in the browser.

Web framework based on PHP

PHP Web framework is

It is a tool that encapsulates common functions of PHP development based on a certain model to enable developers to develop quickly

Its main tasks include:

Code reuse: defining placement and loading rules for packages, classes, and functions. It is recommended to directly integrate Composer and its AutoLoad feature.

Request distribution management: This is routing. Rest-style frameworks like Rewrite. Simpler frameworks mainly use parameters to locate modules and methods.

Configuration file management: loading and dynamic loading of configuration data

Error and exception management: exception capture, error logging and error code specifications.

Layout and template engine: how to plan page layout, how to reuse widgets, how to combine ajax pages, how to redirect expired sessions; how to render data and templates into HTML, whether to compress and set expiration headers.

Database: How to integrate into the controller; what kind of drivers are supported; consider the scalability of master-slave separation; and whether to use ORM

PHP as the best programming language in the world, It is widely used in web development. Because its syntax is similar to C and has a very gentle learning curve, more and more people are using PHP for rapid development of Web products. Many development frameworks have emerged in the PHP world, such as Laravel, ThinkPHP, etc., but regardless of the overall framework, their mode of processing web requests is the same. This article first explains the basic architecture of PHP development of web applications, and then analyzes Laravel separately. and ThinkPHP's processing flow when processing web requests.

Basic architecture of developing web applications with PHP

PHP开发Web应用时所以的请求需要指向具体的入口文件。WebServer是一个内容分发者,他接受用户的请求后,如果是请求的是css、js等静态文件,WebServer会找到这个文件,然后发送给浏览器;如果请求的是/index.php,根据配置文件,WebServer知道这个不是静态文件,需要去找PHP解析器来处理,那么他会把这个请求简单处理后交给PHP解析器。

WebServer会依据CGI协议,将请求的Url、数据、Http Header等信息发送给PHP解析器,接下来PHP解析器会解析php.ini文件,初始化执行环境,然后处理请求,再以CGI规定的格式返回处理后的结果,退出进程。web server再把结果返回给浏览器。整个处理过程如上图所示。

FastCGI

这里的PHP解析器就是实现了CGI协议的程序,每次请求到来时他会解析php.ini文件,初始化执行环境,这就导致PHP解析器性能低下,于是就出现了CGI的改良升级版FastCGI。FastCGI是一种语言无关的协议,用来沟通程序(如PHP, Python, Java)和Web服务器(Apache2, Nginx), 理论上任何语言编写的程序都可以通过FastCGI来提供Web服务。它的特点是会在动态分配处理进程给请求,以达到提高效率的目的,大多数FastCGI实现都会维护一个进程池。FastCGI会先启一个master进程,解析配置文件,初始化执行环境,然后再启动多个worker进程。当请求过来时,master进程会这个请求传递给一个worker进程,然后立即接受下一个请求。而且当worker进程不够用时,master可以根据配置预先启动几个worker进程等待;当然空闲worker进程太多时,也会自动关闭,这样就提高了性能,节约了系统资源。整个过程FastCGI扮演着对CGI进程进行管理的角色。

PHP-FPM

PHP-FPM是一个专门针对PHP实现了FastCGI协议的程序,它实际上就是一个PHP FastCGI进程管理器,负责管理一个进程池,调用PHP解析器来处理来自Web服务器的请求。PHP-FPM能够对php.ini文件的修改进行平滑过度。

新建一个helloworld.php文件,写入下列代码

<?php
  echo"helloworld,";    
  echo"this is my first php script.";
  echophpinfo();
?>

配置好WebServer和PHP-FPM等php运行环境后,在浏览器中访问该文件就可以直接得到输出。

基于PHP的Web框架

PHP Web框架是

基于某模式将PHP开发常用功能封装实现使开发者快速开发的工具

它主要的任务包括:

代码重用:定义包、类、函数的放置和加载规则,建议直接整合Composer及其AutoLoad特性。

请求的分发管理:这个就是路由,Rest风的框架喜欢Rewrite,简单的一点的框架主要通过参数来定位模块和方法所在。

配置文件管理:加载和动态加载配置数据

错误和异常管理:异常捕捉、错误日志记录以及错误码规范。

Layout和模板引擎:如何规划页面布局、widget如何重用、ajax页面如何结合、过期session如何重定向;数据和模板怎么渲染成HTML,是否压缩和设置过期头。

数据库:如何融入控制器;支持什么样的driver;考虑主从分离的扩展性;以及是否使用ORM

相关推荐:

Django用户认证系统(二)Web请求中的认证

The above is the detailed content of How PHP handles the web request process. For more information, please follow other related articles on the PHP Chinese website!

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
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.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development 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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment