The method of realizing asynchronous data invocation in PHP _php techniques

Source: Internet
Author: User

There is only one connection between the browser and the server for connectionless HTTP protocol communication, the characteristics of the connectionless program is client-side request server, the server to return the corresponding program according to the request, can not maintain a durable connection. As a problem, a client's corresponding server may perform 1 seconds and possibly 1 minutes, so that the browser is always waiting, and if the program executes slowly, the user may not be patient enough to turn off the browser.
And sometimes we do not need to care about the results of the implementation of the program, there is no need to waste time and patience to wait, then we have to figure out ways to let the program do not wait in the background silently execution. For example, there is a scenario where a referral message is sent to 1000 users, the user enters or imports a mail account, and the submitting server performs the sending.

<?php 
$count = count ($emailarr);
for ($i =0; $i < $count; $i + +) 
{ 
sendmail ();//Send Message 
} 
?> 

This Code user experience is very poor, also can not actually use, first send so many messages will produce server running timeout, in fact, long time users to wait for the system product suspicion and loss of confidence. However, the user does not need to wait until 1000 messages have been sent to send a successful delivery, we can fully submit after the background directly to the user prompted to send success, and then let the background program to send silently.
This time we need to "execute asynchronously" technology to execute code, asynchronous execution is characterized by silent background execution, the user does not have to wait for the execution of the code results, the benefits of using asynchronous execution:

    • get rid of the application's dependency on a single task
    • Improve program efficiency
    • improves program extensibility
    • Improved user experience in certain scenarios
    • strong> because PHP does not support multithreading, the use of asynchronous calls to request multiple HTTP to achieve the program in parallel execution effect, but note that the request of HTTP too much, will greatly increase the cost of the system

Common way for PHP to execute asynchronously
1. Client page using AJAX technology requesting server
The easiest way to do this is to embed an AJAX call in the HTML code that is returned to the client, or embed an IMG tag, and SRC points to the time-consuming script to execute. This method is the simplest and fastest. The server side does not have to make any calls.
But the downside is, generally speaking, Ajax should be triggered after the onload, that is, the user points to open the page, then close, it will not trigger our background script.
instead of using an IMG tag, this approach is not known as a strict asynchronous execution. User browser for a long time waiting for the execution of PHP script, that is, the user's browser status bar has been shown still in load. Of course, there are other ways to use similar principles, such as script tags, and so on.
2. Popen () function
resource popen (String command, string mode);
opens a pipeline to a process that derives from a given command Make the execution of the result. Opens a pipeline to a process that is generated by the derivation of a given command command. So it can be invoked by calling it, but ignoring its output.
Pclose (Popen ("/home/xinchen/backend.php &", ' R '));
This method avoids the disadvantage of the first method and is also very quick. However, the problem is that this method cannot request another webservice through the HTTP protocol and can only execute local script files. And can only be opened one-way, unable to wear a large number of parameters to the invoked script. And if the traffic is high, a lot of progress will be generated. If the use of external resources, but also to consider their own competition. The
3. Curl Extension
Curl is a powerful HTTP command-line tool that simulates HTTP requests such as Post/get, and then obtains and extracts the data, which is displayed on the "standard output" (stdout).

$ch = Curl_init ();
$curl _opt = Array (curlopt_url, ' http://www.example.com/backend.php ',
       curlopt_returntransfer, 1,
       Curlopt_ TIMEOUT, 1,);
 
Curl_setopt_array ($ch, $curl _opt);
Curl_exec ($ch);
Curl_close ($ch);

Use curl need to set Curopt_timeout to 1 (min 1, depressed). In other words, the client must wait at least 1 seconds.
4. Fscokopen () function
Fsockopen is a very powerful function, support socket programming, you can use Fsockopen to implement the socket program such as mail, and so on, the use of fcockopen need to manually stitching out the header part.

$fp = Fsockopen (www.jb51.net, $errno, $errstr);
if (! $fp) {
 echo $errstr ($errno) <br/>\n ";
} else {
 $out =" get/backend.php/http/1.1\r\n ";
 $out. = "host:www.jb51.net\r\n";
 $out. = "connection:close\r\n\r\n";
 
 Fwrite ($fp, $out);
 /* Ignores execution results
 while (!feof ($fp)) {
  echo fgets ($FP, 128);
 } * *
 fclose ($FP);
}

The above is for you to share 4 kinds of PHP asynchronous implementation of the common way, I hope to help you learn.

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: info-contact@alibabacloud.com 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.