问题描述
在我的 Web 应用程序中,当用户更改其帐户时,我会调用 php mail() 函数向该用户发送电子邮件通知.执行此操作后,我发现帐户更改操作需要非常长的时间(> 20 秒)才能完成.我怀疑这是因为 PHP 等待 mail() 函数发送电子邮件.有没有什么办法可以不用等待就直接调用下一行代码?
In my web application, when a user makes a change to their account, I call the php mail() function to send that user an email notification. After implementing this, I found that the account change action takes a very large amount of time (>20 seconds) to complete. I suspect that this is because PHP waits for the mail() function to send the email. Is there any way to make this call without waiting and immediately continue to the next line of code?
谢谢,
保罗
推荐答案
创建另一个 PHP 脚本(在本示例中,我们将其称为mailuser.php").在此文件中,您的代码将查找尚未通过电子邮件发送的已激活帐户...然后发送电子邮件.
Create another PHP script (we'll call it "mailuser.php" for this example). In this file your code would look for activated accounts that haven't been emailed yet... then send the email.
在您的原始代码中(激活帐户后)调用:
In your original code (after activating the account) call :
exec("php mailuser.php > /dev/null 2>&1 &");
这应该会产生进程,而不是等待它返回.
This should spawn the process, but not wait for it to return.
有关更多信息,请参阅以下帖子:phpexec 命令(或类似命令)不等待结果 &异步运行 PHP 任务
For more information, see these posts : php exec command (or similar) to not wait for result & Run PHP Task Asynchronously
您也可以选择在命令行上传递用户 ID,这样 mailuser.php 就不必根据字段/标志查找用户.
You could also elect to pass the user id on the command line, so that the mailuser.php doesn't have to look for the users based on a field/flag.
这篇关于防止 PHP 等待 mail() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!