


Solve the problem of AJAX request making PHP response time too long
Now we have developed many applications that rely on Ajax requests. In some cases, even entire pages rely on Ajax. Sometimes we will notice that when a web page sends two or more Ajax requests, PHP's response time will be very long and the response content will be returned at the same time.
This problem is most likely caused by the way you handle PHP sessions. Follow this article to understand this problem and do something to avoid it.
Content
What is a PHP session?
What is Ajax?
Specific problem
Cause
Solution to the problem
Summary
What is a PHP session?
In order to understand this problem, it is necessary to first understand PHP sessions and Ajax, and how they interfere.
Suppose you are developing a web application and want to identify different users. You want to remember who visited all pages each time without logging in. In this case, you can use cookies or sessions.
As you may have realized, sessions are a way of storing user information that can be retrieved on any page. Unlike Cookies, Sessions are stored on the server, and no user can directly change this information.
By default, Sessions are valid until the user closes the browser, or expires after the user has been inactive for a period of time specified in the PHP configuration file.
In a PHP page, whenever you want to store or retrieve user data, you must call session_start() at the beginning of the page, so you have permission to use $_SESSION to obtain session data.
What is Ajax?
Ajax stands for Asynchronous JavaScript and XML, it is a way to send data to and receive data from the server without reloading the entire page.
We use this way to send data and retrieve it from the server faster. We don't have to get the entire page and render it in the browser because that's slow.
Therefore, we can update a portion of a page and have the change visible to the user, like a user scrolling down a Facebook timeline page to see what they want to see, as new content is added without having to reload the entire page.
Specific questions
Developing web applications that are almost 100% based on Ajax is nothing new, but when a web page sends two or more Ajax requests at the same time, you will notice that the request will take a long time, and The request was completed almost at the same time.
The reason
When you want the server to send an Ajax request, the PHP script also opens session_start(), and its call will lock the PHP session file.
As you may already know, PHP stores session data in files on the server by default. Because only one PHP request can change the same session file, two simultaneous PHP requests may cause a typical file lock condition, so any other session_start() request called by PHP for the same user will have to wait until The first request ends.
Now, most PHP frameworks will first use session_start() in the main file. Therefore, if you are using a framework or library that calls session_start(), it will cause a session file lock, which will delay simultaneous Ajax requests to the same user using the same browser.
Solution to the problem
Calling the session_write_close() function will cause PHP to write the session file and close it, so after the session file is released, another request will have permission to write.
After calling session_write_close(), the current script will continue to run normally, but you should know that no session variables are allowed to be changed after calling session_write_close(); in the same script, other requests sent to PHP at the same time can lock the session file and change session variables.
To allow you to see this kind of problem, I created test code and uploaded it to github. You can find the test script here. Locally, you need to use an instance to use the test code, then open the browser console to view the request and response times.
As we see in the sample code in this file, if we create multiple requests like the following code...
1 2 |
|
Each request for the same user will wait until the previous request is completed before it is completed. It will take 5 seconds because the session file is not released until the script is completed. Therefore, when session_start() is called for the first time, new requests will be blocked. That would kill the idea of asynchronous requests, that is, multiple requests being sent and executed at the same time.
If you change the code in the file:
1 2 3 |
|
The third line of code will release the session file lock, so another concurrent request can run without waiting because it can call session_start() without any problems.
Summary
PHP is a bit subtle and will make you worry about why strange things are happening. But once you understand how things work, everything makes sense and you can think better about solving problems.
Translation source: http://www.ido321.com/1577.html
This article is translated based on @Eslam Mahmoud's "Fix the AJAX Requests that Make PHP Take Too Long to Respond". The entire translation contains my own understanding and thoughts. If the translation is not good or there is something wrong, please ask a friend who works in the same field. Guidance. If you want to reprint this translation, please indicate the English source: http://www.phpclasses.org/blog/post/277-Fix-the-AJAX-Requests-that-Make-PHP-Take-Too-Long-to- Respond.html
The above introduces how to solve the problem of AJAX request causing PHP to take too long to respond, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
