php - 在后台执行脚本
问题描述
我一直在尝试处理的代码有一个小问题。我试图在我的项目中的不同时间使用 php 发送邮件,其中大多数是用户触发的。由于有不同的邮寄点和页面,我创建了一个邮寄脚本,我将所有邮寄请求发送到其中(这样,所有电子邮件都从一个页面发送)。
例如,注册后,注册脚本中的验证码会发送到邮件脚本,该邮件脚本会向用户发送验证电子邮件。然后注册脚本在重定向到下一页之前等待来自邮件脚本的响应。但是由于很多因素,邮件脚本需要一些时间来加载。
我不希望用户遇到这种延迟,因此我一直在寻找一种在后台将数据发送到邮件脚本的方法,同时将用户重定向到另一个页面,而不是等待邮件脚本的响应.
我曾尝试使用 AJAX 直接从前端发送数据,但我使用验证过程,其中某些值是从数据库中验证的,因此我必须从注册脚本发送。我一直在寻找与 AJAX 等效的 php,在此我不必在重定向用户之前等待来自邮件脚本的响应。我已经尝试过 CURL,但不知何故,它仍然在等待响应。
这是我的 cURL 代码:
$url = "https://requiredurl";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
$data = curl_exec($ch);
curl_close($ch);
header("location: returnurl");
exit();
我希望它在执行 cURL 命令后立即重定向到重定向 URL,而无需等待响应。
我需要任何其他 php 方法的帮助,我可以用它来工作。提前致谢。
解决方案
如果您确实通过注册脚本收集用户信息,我认为使用 GET 方法并不安全。您应该使用 POST 方法:
$postData = array(
"data1" => "Test Data1",
"data2" => "Test Data2",
"data3" => "Test Data3"
);
$url = "https://requiredurl";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
但是,如果您决定继续,可能对您有用的东西是删除curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
或者您可以轻松地将其注释掉。这样,命令运行,但 cURL 不会发回或显示任何响应。
这是不可取的,因为您不知道该命令是否运行,但它至少可以解决您的问题。
另一种方法
将添加此代码:
// don't let user kill the script by hitting the stop button
ignore_user_abort(true);
// don't let the script time out
set_time_limit(0);
// start output buffering
ob_start();
// If you need to return data to the browser, run that code
// here. For example, you can process the credit card and
// then tell the user that their account has been approved.
usleep(1500000); // delay before redirecting user
// now force PHP to output to the browser...
$size = ob_get_length();
header("Content-Length: $size");
header('Connection: close');
ob_end_flush();
ob_flush();
flush();
// everything after this will be executed in the background.
// the user can leave the page, hit the stop button, whatever.
usleep(2000000); // delay before executing background code
在邮件功能行之前。
这样,当用户被重定向到另一个页面时,代码将在后台执行。
我希望这有帮助
推荐阅读
- php - 在 foreach 循环中多次运行 PHP 文件
- android - 在recyclerview中更改所选项目的背景颜色
- c - 了解发布顺序并与 C11 同步
- playframework - 设置cookie作为响应
- python - Pandas - 使用 read_csv 指定具有混合列数据的 dtype
- linux - 为什么我的 BPF_PROG_TYPE_CGROUP_SKB 程序不能在容器中运行?
- django - 在整个 django 项目会话期间仅加载字典和列表一次
- django - 如何在 django 查询中过滤外键对象?
- r - 重新排列数据框中的行
- dart - 返回上一个屏幕时如何捕捉价值?