dongxinche1264 2015-11-12 14:32
浏览 66
已采纳

获取PHPUnit ajax测试的cookie

I'm trying to write some PHPUnit tests for ajax endpoints. I can do this no sweat when the user doesn't have to be logged in. But to test the endpoint in question, the user does have to be logged in and I want to get the cookie programmatically as part of the test. Basically the test I want to run looks like:

    $url = "https://example.com/ajax/endpoint";
    $fields = array(
        'name'=>'test '.rand(),       
        'host'=>rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255),
        'port'=>rand(1,1000)
    );
    $fields_string = "";
    foreach ($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = rtrim($fields_string, '&');
    ob_start();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_COOKIE, $userCookie);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    $this->assertEquals(true, $response);
    $json = ob_get_contents();
    $return = json_decode($json);
    $this->assertEquals('false', $return->success);
    $this->assertEquals('', $return->data);
    ob_end_clean();

But I don't know a good way to get $userCookie other than opening a browser, logging in, and then reading PHPSESSID from the cookies in the browser. How can I get the cookie for this without grabbing it manually? I'd like to be able to get it from a curl request to the login endpoint:

    $url = "https://example.com/ajax/login";
    $fields = array(
        'username'=>$username,
        'password'=>$password
    );
    $fields_string = "";
    foreach ($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
  • 写回答

2条回答 默认 最新

  • duannao3402 2015-11-12 14:56
    关注

    Does anything stop you to grab it programmatically?

    $ch = curl_init('https://example.com/login');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "login=root&password=toor");
    curl_setopt($ch, CURLOPT_HEADER, 1);
    
    $result = curl_exec($ch);
    preg_match_all('/^Set-Cookie: PHPSESSID=(.*?);/mi', $result, $matches);
    $userCookie = $matches[1];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 halcon联合c#遇到了问题不能解决
  • ¥15 xshell无法连接提示ssh服务器拒绝密码
  • ¥15 AT89C52单片机C语言关于串口通信的位操作
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?