


PHP asynchronous: Use fsockopen curl to implement functional methods similar to asynchronous processing in PHP
PHP is a process-oriented language from a mainstream perspective. Its biggest disadvantage is that it cannot achieve multi-thread management. The execution of its program is from beginning to end, and it is executed according to logic all the way. Branches are impossible. This is One of the reasons that restricts PHP from developing into a higher-level language among mainstream programming languages.
In PHP, sometimes we actually want to perform another operation at the same time when performing a certain operation. Take a scenario: when users are grabbing tickets, you do not want users to queue up to connect to the database for query. Judge, insert, and then return the user results after completion. In fact, we don’t need the user to wait that long. After the user submits, we can directly tell him that he has successfully grabbed the ticket. As for the various operations, we can just leave it to the background for processing. Of course, we now use message lists to handle this situation. We store each request submitted by the user in a message queue to tell the user that it has been completed. After the user happily closes the page, in fact, the background is still receiving messages one by one. Remove the request from the queue for operation. Our article uses a heterogeneous approach to enable operations to run in the background without the user having to wait.
First, we need to create a request entry:
Submitted data
Submit to the background
Tell the user that it has been done
Secondly, we need a background handler to check whether the user is online It does not affect its operation:
<?php ignore_user_abort(true); set_time_limit(0);
Incoming data
Data processing
Now the question is, in the first piece of code, how to "submit to the background"? We implement this function through a non-blocking request. That is to create a url that can be accessed, run the second program on this url, and request the url through a request, thus activating the automatic running of the second program.
Next let’s look at the code directly:
// 远程请求(不获取内容)函数 function _sock($url) { $host = parse_url($url,PHP_URL_HOST); $port = parse_url($url,PHP_URL_PORT); $port = $port ? $port : 80; $scheme = parse_url($url,PHP_URL_SCHEME); $path = parse_url($url,PHP_URL_PATH); $query = parse_url($url,PHP_URL_QUERY); if($query) $path .= '?'.$query; if($scheme == 'https') { $host = 'ssl://'.$host; } $fp = fsockopen($host,$port,$error_code,$error_msg,1); if(!$fp) { return array('error_code' => $error_code,'error_msg' => $error_msg); } else { stream_set_blocking($fp,true);//开启了手册上说的非阻塞模式 stream_set_timeout($fp,1);//设置超时 $header = "GET $path HTTP/1.1\r\n"; $header.="Host: $host\r\n"; $header.="Connection: close\r\n\r\n";//长连接关闭 fwrite($fp, $header); usleep(1000); // 这一句也是关键,如果没有这延时,可能在nginx服务器上就无法执行成功 fclose($fp); return array('error_code' => 0); } }
We created a function based on fsockopen. In this function, fsockopen is used to access the url. However, during the access, it is not required to obtain the content displayed in the url, but only issues Access request, close this access immediately after the request arrives. The advantage of this is that there is no need to wait for the visited URL to return reliable information, which saves time. The execution time of this code is between 0.1-0.2 seconds, which is almost imperceptible to ordinary visitors. Therefore, when using it, you only need to call this function and the corresponding url. However, there is no data transmission part provided here. How to transmit data, in fact, you only need to add the post content to $header.
In addition to fsockopen, curl can actually achieve this effect. Some hosts do not support fsockopen, so we can use curl to achieve it.
function _curl($url) { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_TIMEOUT,1); $result = curl_exec($ch); curl_close($ch); return $result; }
The key to this code is to provide a Timeout, only 1 second, which means that curl makes a request, regardless of whether the returned content is received, the access will be closed after 1 second, so the execution of this function The data is between 1.0-1.1 seconds. But for users, if it is an application that requires data processing, the wait of 1 second is almost ignored. If you want to use a simpler and easier-to-understand code, you can choose curl to implement it.

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

AI Hentai Generator
Generate AI Hentai for free.

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

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

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

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

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,

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.
