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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化