Implement asynchronous calling multithreaded program code in PHP

Source: Internet
Author: User
Tags curl php script mail account

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.

The code is as follows Copy Code

<?php

$sqlserver/42852.htm Target=_blank >count=count ($emailarr);

for ($i =0; $i < $count; $i)

{

SendMail (...); /Send mail

}

?>

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:

1. Get rid of the application's dependency on a single task

2. Increased efficiency in the execution of procedures

3. Improve the program's scalability

4. Improve the user experience in a certain scenario

5. 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 is too much HTTP, will greatly increase the overhead of the system


User experience: User waits for-> to send complete
Friends will ask, how is missing the letter link?
OK, the letter link is when the user submits the request, send the letter to a separate processing of the letter of the PHP program processing, when the user saw "sent" when the letter has not been sent, this time, the sending program is working in the background work, a Feng Yi to send out

sendmail.php

  code is as follows copy code

<?php
$domain =" www.***.com ";
$url ="/system_mail.php ";
$par =" Email= ". Implode (', ', $emailarr)." .......
$header = "POST $url http/1.0rn";
$header. = "CONTENT-TYPE:APPLICATION/X-WWW-FORM-URLENCODEDRN";
$header. = "Content-length:". Strlen ($par). "Rnrn";
$fp = @fsockopen ($domain, $errno, $errstr, 30);
Fputs ($fp, $header. $par);
Fclose ($fp);

Echo ' send complete ';

system_mail.php
<?php
Ini_set ("Ignore_user_abort", true);
Ignore_user_abort (true); The code here requires php.ini to open the relevant options to ensure that PHP execution does not time out, do not understand, refer to my other article "Close the browser, PHP script will continue to run"
//Get email address, send a letter, here is the letter code
?

OK, after the asynchronous way, the user submits the information, can immediately get the result "send complete". Letter, will be in the background of a Feng Yi sent, until the sending finished.


After testing, summed up several methods, and everyone share:
1. The easiest way to do this is to embed Ajax calls into 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 disadvantage 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.
In the case of an IMG tag, this approach cannot be called 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 ()

Resource Popen (String command, string mode);
Opens a pipeline to a process that is generated by the derivation of a given command command. 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.

The code is as follows Copy Code
Pclose (Popen ("/home/xinchen/backend.php &", ' R '));

This method avoids the drawbacks 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.

3. Use of Curl
This method, set Curopt_timeout to 1 (minimum 1, depressed). In other words, the client must wait at least 1 seconds.

  code is as follows copy code

$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);

4. Using Fsockopen
This method should be the most perfect, but the downside is that you need to spell out the header portion of HTTP yourself.

  code is as follows copy code

$fp = Fsockopen ("www.example.com", $errno, $errstr);

if (! $fp) {

    echo "$errstr ($errno) <br/>n";

} else {

     $out = "Get/backend.php/http/1.1rn";

     $out. = "HOST:WWW.EXAMPLE.COMRN";

     $out. = "Connection:closernrn";

 

    fwrite ($fp, $out);

    /* Ignore execution results

while (!feof ($fp)) {

echo fgets ($FP, 128);

}*/

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