通过PHP中的HttpRequest和请求一起发送cookie


Send cookies via HttpRequest in PHP along with request

我有一个PBX服务器(Asterisk 1.8),我能够通过请求中的一些GET变量来管理调用。我的问题是,我需要首先登录到服务器。一旦我这样做了,我想保存一个cookie,然后把它和我的下一个请求一起发送进行验证。

我有目前使用cURL:的代码

public function authenticate(){
    $temp_dir = sys_get_temp_dir();
    $ckfile = tempnam($temp_dir, "ast");
    $auth_url = $this->ast_link."?action=login&username=asterisk_http&secret=*****";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $auth_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $auth_response = curl_exec($ch);
    curl_close($ch);
    $this->auth_cookie = $ckfile;
    return $ckfile;
}
//$call contains id, patcode, phone_number, call_type
public function makeCall($overload, $call, $exten, $user = NULL){
    set_time_limit(0);
    if(!$this->auth_cookie) $this->authenticate();
            //http://blah.server/asterisk/rawman?action=originate&channel=$somechannel
    $call_url = $this->generateCallUrl($overload, $call, $exten, $user);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $call_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $this->auth_cookie);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

不幸的是,cURL等待来自服务器的响应,这种情况只发生在调用结束时。正因为如此,我无法同时拨打多个电话。

我如何在PHP中使用HttpRequest以与cURL相同的方式发送cookie和请求?我对这背后的网络机制有点不熟悉,所以请原谅我在这方面的无知。

TL;DR:如何将cookie与HttpRequest 一起发送

关于"如何将cookie与HttpRequest一起发送"的问题,我认为我可能会提供帮助,因为我刚刚解决了一个类似的问题。

首先,每当你想知道网络级别发生了什么,即收到了什么类型的请求和发送了什么类型,一定要在合唱控制台中查找"网络"选项卡。或者,你可以下载并安装FireBug,它将帮助你监控传入和传出的请求(这些提示将在你的下一个项目中真正帮助你)。

至于通过HTTPHeader设置cookie,只需使用以下php代码。

header('Set-Cookie: CookieName='.$content);

这里的Cookie名称是任何会话Cookie的名称,即JSESSIONID等,内容是每次客户端需要进行身份验证时都必须调用的相关密钥。

我希望这些信息能帮助您和其他开发人员:)