PHP asynchronous socket call implementation code

Source: Internet
Author: User
Tags email account

PHP asynchronous call Implementation Method
The browser and server communicate with each other over the connectionless HTTP protocol. connectionless programs are characterized by client requests to the server. The server outputs the corresponding program according to the request, persistent Connections cannot be maintained.
In this case, a problem occurs. The corresponding server of a client may execute for 1 second or 1 minute, so that the browser will remain in the waiting state. If the program runs slowly, the user may be impatient to close the browser.
Sometimes, we do not need to care about the results of program execution, and there is no need to waste time and patience, so we have to figure out a way for the program to wait for silent execution in the background.
For example, in the current scenario, a recommendation email is sent to 1000 users. The user enters or imports the email account and submits it to the server for sending.
Copy codeThe Code is as follows:
<? Php
$ Count = count ($ emailarr );
For ($ I = 0; $ I <$ count; $ I ++)
Sendmail (...); // send an email

The user experience of this code is very poor and cannot be used in practice. First, sending so many emails will result in server operation timeout. In fact, a long waiting time will cause the user to doubt and lose confidence in the system products. However, you do not need to wait until all the 1000 emails are sent before submitting the email successfully. You can submit the email to the backend and then send the message to the user.
At this time, we need the "Asynchronous execution" technology to execute code. asynchronous execution is characterized by silent execution in the background, and users do not have to wait for the code execution results. The advantages of asynchronous execution are as follows:
1. Get rid of the application's dependency on a single task
2. Improved program execution efficiency
3. Improved Program scalability
4. Improved user experience in certain scenarios
5. because PHP does not support multithreading, the asynchronous call of multiple HTTP requests achieves parallel execution of the program. However, if there are too many HTTP requests, the system overhead will be greatly increased.
Common PHP asynchronous execution methods:
1. Client pages use AJAX technology to request servers
1. The simplest method is to embed an AJAX call in the HTML code returned to the client, or embed an img tag. src points to the time-consuming script to be executed.
This method is the simplest and fastest. The server does not need to make any calls.
However, the disadvantage is that Ajax should be triggered after onLoad. That is to say, when the user clicks the page and closes it, the background script will not be triggered.
Using the img label cannot be called a strictly asynchronous execution. The user's browser will wait for a long time until the php script is executed, that is, the status bar of the user's browser is still being loaded.
Of course, you can also use other similar methods, such as script labels.
2. popen () function
Resource popen (string command, string mode );
// Open an pipeline pointing to a process. This process is generated by the execution of the derived command. Open an pipeline pointing to a process, which is generated by running the command derived from a process.
Therefore, you can call it, but ignore its output.
Pclose (popen ("/home/xinchen/backend. php &", 'R '));
This method avoids the disadvantages of the first method and is also very fast. However, the problem is that this method cannot request another WebService through the HTTP protocol and can only execute local script files. In addition, it can only be opened in one way, and a large number of parameters cannot be used to call scripts.
In addition, if the traffic is high, a large number of processes will be generated. If external resources are used, you must consider competition on your own.
3. CURL Extension
CURL is a powerful HTTP command line tool that can simulate POST/GET and other HTTP requests and then obtain and extract data, which is displayed on stdout.
Copy codeThe Code is as follows:
$ Ch = curl_init ();
$ Curl_opt = array (CURLOPT_URL, 'HTTP: // ',
Curl_setopt_array ($ ch, $ curl_opt );
Curl_exec ($ ch );
Curl_close ($ ch );

To use CURL, set CUROPT_TIMEOUT to 1 (minimum: 1, depressing ). That is to say, the client must wait at least 1 second.
4. fscokopen () function
Fsockopen is a very powerful function that supports socket programming. You can use fsockopen to implement socket programs such as email sending. To use fcockopen, You need to manually splice the header part.
Official documents:
Copy codeThe Code is as follows:
$ Fp = fsockopen ("", 80, $ errno, $ errstr, 30 );
If (! $ Fp ){
Echo "$ errstr ($ errno) <br/> \ n ";
} Else {
$ Out = "GET/backend. php/HTTP/1.1 \ r \ n ";
$ Out. = "Host: \ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
Fwrite ($ fp, $ out );
/* Ignore execution results
While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
Fclose ($ fp );

PHP asynchronously calls socket
Copy codeThe Code is as follows:
$ Host = " ";
$ Path = "/Report. php? ReportID = 1 ";
$ Cookie = Session_id ();
$ Fp = fsockopen ($ host, 80, $ errno, $ errstr, 30 );
If (! $ Fp ){
Print "$ errstr ($ errno) <br/> \ n ";
$ Out = "GET". $ path. "HTTP/1.1 \ r \ n ";
$ Out. = "Host:". $ host. "\ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
$ Out. = "Cookie:". $ cookie. "\ r \ n ";
Fwrite ($ fp, $ out); // write requests to the socket
// You can also choose to obtain the server Response
/* While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
// Close the socket directly without waiting for the response from the server.
Fclose ($ fp );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.