php 在 curl 完成执行前重定向

php redirect before curl completes execution

所以我们有一个系统可以改变您在显示器上看到的内容。此代码旨在将 "argument" 命令发送到 JQuery 页面。

curl 工作得很好,但是当我们注释掉处理重定向到 XML 文档的 if 语句时。发生重定向,但未执行 Curl 请求。我们需要了解为什么会发生这种情况,当我们删除重定向时它会运行 curl 请求。当重定向到位时,不会执行 curl 请求。

请帮助找出这个问题的原因和纠正问题的方法,我们必须保留重定向,但如果有更好的 运行 curl 请求方法,即不使用 curl,但很棒的东西,任何建议都会被测试。

<html>
<head>
<?php
    ob_implicit_flush(false);
    $argument = $_GET["argument"];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "http://example.com/sub/page.html?api_key=**********&device_id=************&argument=".$argument."");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);

  if($argument == 1) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service1.xml">';
  } else if($argument == 2) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service2.xml">';
  } else if($argument == 3) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service3.xml">';
  } else if($argument == 4) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service4.xml">';
  }
?>
</head>
</html>

据我所知,curl 请求可能还没有完成,这是在页面执行重定向之前发生的事情。为什么不从 curl 请求中获取 return 值并将其用作后面的 if 语句的先决条件?

即:

$status=curl_getinfo( $ch, CURLINFO_HTTP_CODE );

if( $status==200 ){
  if($argument == 1) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service1.xml">';
  } else if($argument == 2) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service2.xml">';
  } else if($argument == 3) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service3.xml">';
  } else if($argument == 4) {
       echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service4.xml">';
  }
}

根据您的观点,我可以得出以下几点。

  1. PHP 程序 运行 按顺序执行,因此显然 curl 执行将 运行 在第一步然后重定向到 XML 文档。

这是因为curl执行时间会很长

  1. 确保在 curl 成功后重定向页面

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($status == 200){
        if($argument == 1) {
            echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service1.xml">';
        } else if($argument == 2) {
            echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service2.xml">';
        } else if($argument == 3) {
            echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service3.xml">';
        } else if($argument == 4) {
            echo '<META http-equiv="refresh" content="0;URL=http://adloc8tor.com/ussd/service4.xml">';
        }
    }