dongzhao2725
dongzhao2725
2015-11-26 16:39

使用curl登录WS1

已采纳

I'm trying to login into ws1.com using curl, however whenever i put the POST to true I'm getting error: Bad Request, this is the code that i tried:

<?php
$LOGINURL = "https://secure2.ws1.com/login";
$agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "_csrf=QTRvNkJKaUoWBFYDBHkLDHFkP0MdMhAPOUZCASR9Xh4ZRDx7BC8LGA%3D%3D&LoginForm%5Bemail%5D=naczzalid%40hotmail.com&LoginForm%5Bpassword%5D=csc1233&LoginForm%5BrememberMe%5D=0&login-button=");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
echo $result = curl_exec ($ch);
curl_close ($ch);
?>

Anyone please can explain to me what is the problem in this so i can learn how to do it?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douna2633 douna2633 6年前

    I tested some things with this form and if the csrf code is incorrect, then it gives a bad request.

    The csrf value changes for every request and is tied to your cookies. So you need to fetch the login page first and extract the correct csrf code before submitting.

    Working code:

    <?php
    $LOGINURL = "https://secure2.ws1.com/login";
    $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$LOGINURL);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
    $result = curl_exec ($ch);
    
    // extract csrf token
    preg_match('/<input type="hidden" name="_csrf" value="([^"]+)">/i', $result, $csrf);
    $csrf = $csrf[1];
    $csrf = urlencode($csrf);
    
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "_csrf={$csrf}&LoginForm%5Bemail%5D=naczzalid%40hotmail.com&LoginForm%5Bpassword%5D=csc1233&LoginForm%5BrememberMe%5D=0&login-button=");
    
    $result = curl_exec($ch);
    
    curl_close ($ch);
    
    var_dump($result);
    
    点赞 评论 复制链接分享

相关推荐