php是否等待API调用的响应?


Does php wait for a response from an API call?

如何从php脚本中调用外部域?是卷曲吗?如果是这样,php在继续之前等待该行被处理,以便我们可以确定返回的数据。

从外部URL获取响应的最简单方法是使用file_get_contents(),但是如果您想要更多选项或发送post数据,cURL绝对是更好的方法。但是,这两个函数都等待响应。PHP非常直接

您可以使用Curl, file_get_contents(加载适当的扩展)或做一些套接字工作。

class Tools
{
public static function post_request($url, $datos) 
{
    $resultado=null;
    $datos=http_build_query($datos);
    $url=parse_url($url);
    // extract host and path:
    $host=$url['host'];
    $ruta=$url['path'];
    $socket=fsockopen($host, 80, $errno, $errstr, 30);
    if($socket)
    {
        // send the request headers:
        fputs($socket, "POST $ruta HTTP/1.1'r'n");
        fputs($socket, "Host: $host'r'n");
        fputs($socket, "Content-type: application/x-www-form-urlencoded'r'n");
        fputs($socket, "Content-length: ". strlen($datos) ."'r'n");
        fputs($socket, "Connection: close'r'n'r'n");
        fputs($socket, $datos);
        while(!feof($socket))
        {
            $resultado.= fgets($socket, 128);
        }
    }
    else die('ERROR');
    fclose($socket);
    $resultado=explode("'r'n'r'n", $resultado, 2);
    $header=isset($resultado[0]) ? $resultado[0] : '';
    $contenido=isset($resultado[1]) ? $resultado[1] : '';
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $contenido
        );
    }
};

如果我没记错的话,在请求被处理之前,脚本不会继续。

是-使用cURL,它将等待回复(或失败)。