I have a question about how does php code execute.
I am now only using php to connect to the mysql DB for iOs APP. So I create different APIs at php side. Then, at APP side, just submit post or get request to inquiry or update the DB.
So at php side, I did DB inquiry or update then return a json result to the APP.
Now I have a function, it does the following job:
function a(){
1.Insert a record to the DB;
if (insert successful){
2. $this->echoJson ('Succeed','New Record has added');
3. then send email to several email addresses.(using PHPMailer-master)
}
}
When my APP side get the json data that indicates insertion is successful. The app will jump to another page.
The function works well. The only problem is step 3 takes around 5 seconds to run. Step 1 and 2 is very fast. It seems for the php side, it only returns the json data when all the codes have been executed. So my APP side needs to wait for 5 seconds to get the response. But I only care about if the insertion is successful.
Is it possible to return the json data once the insertion is successful then do the sending?
I am not sure if I explain the problem clearly.
In summary, I found the execution order is step 1 step 3 step 2. I want to make the order as step 1 step 2 step 3.
Thank you.
Move your PHPMailer funtion to another file (lets say send.php
, which can be reached internally by http://example.com/send.php
). Then you can make a curl request with a tiny timeout function that actually sends the mail.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/send.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_exec($ch);
curl_close($ch);
I understand your issue but no, it must finish sending the mails before the json returns. PHP does not support threading unlike other High level language, if there is a way you keep the mails like in DB and run a cron job at a time to push all mails and not sending it when its returning the json
Vicotry's solution works with minor edit:
curl_setopt($ch, CURLOPT_URL, "sendActiveEmail.php");
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10);
$parmArray=array("paraName"=>value,...);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parmArray);
curl_exec($ch);
curl_close($ch);