Implementing asynchronous calling multithreaded program code in PHP _php tutorial

Source: Internet
Author: User
Tags mail account
This article describes in detail the implementation of the asynchronous multi-threaded method in PHP, the following we send to 1000 users a referral message, the user entered or import the mail account of the submission server to perform the send to tell.

For example, there is a scene, to send 1000 users a referral mail, the user input or import mail account to submit the server to perform the send.

The code is as follows Copy Code

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

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

{

SendMail (...); /Send mail

}

?>

This Code user experience is very poor, and can not actually use, the first to send so many messages will result in server run time-out, in fact, long user wait time will let users doubt and loss of confidence in the system products. However, the user does not have to wait until 1000 messages have been sent complete before the submission is successful, we can submit the background directly to the user prompt to send the success, and then let the background program silently sent.

This time we need "asynchronous execution" technology to execute code, asynchronous execution is characterized by the background of silent execution, the user does not have to wait for the result of code execution, using the benefits of asynchronous execution:

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

2. Improved execution efficiency of the program

3. Improve the extensibility of the program

4. Improved user experience in a certain scenario

5. Because PHP does not support multi-threading, the use of asynchronous calls to request more than one HTTP way to achieve the program parallel execution effect, but note that the request of excessive HTTP, will greatly increase the system overhead


User experience: User waits, Send complete
Friends will ask, how to lack the sending link?
OK, send a link in the user submits the request, the letter to the task to a separate processing of the PHP program processing, when the user saw the "send complete" when the fact that the message has not been sent, this time, the sending process is working in the background, a lunar sealed outward sent

sendmail.php

code 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 needs to php.ini 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 not continue to run"
//Get an email address, Send the letter, here is the letter code
?

Well, after changing to asynchronous mode, the user submits the message and can immediately get the result "sent over". Letter, will be in the background of a lunar sealed send, until the completion of the transmission.


After testing, summed up several methods, and everyone share:
1. The simplest approach is to embed an AJAX call in the HTML code returned to the client, or embed an IMG tag, which 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.
However, the disadvantage is that, in general, 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. The user's browser waits for the execution of the PHP script to complete, that is, the status bar of the user's browser is always displayed in load.
Of course, you can also use other similar principles, such as script tags and so on.

2. Popen ()

Resource Popen (String command, string mode);
Opens a pipeline that points to a process that is generated by the execution of a derived command command. Opens a pipeline that points to a process that is generated by the execution of a derived command command.

So you can call it, but ignore its output.

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

This method avoids the disadvantage of the first method and is also very fast. However, the problem is that this method cannot request another webservice through the HTTP protocol, only local script files can be executed. And can only be opened one way, unable to wear a large number of parameters to the called script.
And if, when the traffic is very high, there will be a lot of process. If you use external resources, consider the competition yourself.

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

The 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 perfect one, but the downside is that you need to spell out the header part of HTTP yourself.

The code is as follows Copy Code

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

if (! $fp) {

echo "$errstr ($errno)
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);

}


http://www.bkjia.com/PHPjc/444683.html www.bkjia.com true http://www.bkjia.com/PHPjc/444683.html techarticle This article describes in detail the implementation of the asynchronous multi-threaded method in PHP, the following we send to 1000 users a referral mail, the user entered or import mail account of the submission service ...

  • Related Article

    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.