【问题标题】:block execution of php script in ajax request在ajax请求中阻止执行php脚本
【发布时间】:2018-09-29 15:12:41
【问题描述】:

我的小应用程序是这样工作的:在一个简单的文本输入中,要求用户插入一个 url。在更改时,我的脚本会尝试提取并显示在此页面上找到的前 10 张图像。

<input type="text" name="url" id="url" value="">

$("form.link-form input#url").change(function() {
  var request =     $.ajax({
                      type: "GET",
                      url: "funzioni/ajax/loadImagestFromUrl.php",
                      data: "url=" + insertedUrl,
                      dataType: "html",
                      timeout: 5000,
                      success: function(res) {
                        loadUrlImages2div(msg99);
                      },
                      error: function() {
                         request.abort();
                      }
                    });
});

PHP 脚本 loadImagestFromUrl.php 运行此代码,使用 PHP Simple HTML DOM Parser 库:

set_time_limit(5);
$html = file_get_html($url); // load into this variable the entire html of the page
$count=1;
foreach($html->find('img') as $key=>$element) { // only images
    if ($count==11) break; //only first 10 images
        echo "<img class=\"imgFromUrl\" src=\"".$element->src."\" />\n";
    }
    $count++;
}

这在大多数情况下都很好用,但是有些 url 在几秒钟内不可用,或者受密码保护,即使我为 ajax 请求设置了 5 秒的超时时间和 5 秒的超时时间,服务器也会继续执行某些操作执行php代码。

当这种情况发生时,一切都会被阻止,甚至刷新页面也是不可能的,因为它会加载和加载,并且只有在很长一段时间后才会返回“504 Gateway Time-out。服务器没有及时响应。”

有人可以帮助我了解如何完全阻止此请求并让服务器继续工作吗?

【问题讨论】:

  • 简而言之,ajax响应发送请求并等待应答。如果您取消等待答复,则由您的请求启动的脚本不会停止(它不知道您已停止等待)。因此,如果您想阻止服务器在设定的时间后尝试,您需要在后端执行此操作。一旦你决定取消,你应该向 ajax 返回一个响应,通知它应该停止等待。
  • 另请注意,当 PHP 在 safe mode 中运行时,set_time_limit() 无效。没有解决方法。
  • 如果您能够使用 cURL 模块,您可以使用它在其选项中指定超时。见stackoverflow.com/a/26877132/694400

标签: php jquery ajax image


【解决方案1】:

知道解决方案必须在 php 代码超时而不是 ajax 超时中找到。这很清楚。

我发现了这个有趣的讨论 Great answer: Handling delays when retrieving files from remote server in PHP 这建议在 file_get_contents 函数中使用上下文参数。 但实际上它不适用于我的应用程序。

因此,正如 Wieger 所建议的,我尝试使用 curl 而不是 file_get 内容。我定义了这个函数

function file_get_contents_curl($url) {
  $ch = curl_init();
  $timeout=2;

  curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

  $data = curl_exec($ch);
  curl_close($ch);

  return $data;
}

并在解析器库中使用它而不是 file_get_contents。

同样,它适用于大多数情况,但某些 url 会使服务器加载很长时间,直到网关超时。

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2011-10-30
    • 2014-11-05
    • 2019-11-04
    • 2012-07-04
    • 2011-11-06
    相关资源
    最近更新 更多