dpsyssiv90846 2014-04-05 18:41
浏览 99
已采纳

如何在php中进行curl并保存会话,并最终使用会话变量

I have tried to simulate mass login using javascript, by pasting a bunch of codes in the google chrome console.

These is what I basically do:

var data = [{u:1, p:1}, {u:2, p:2}, {u:3, p:3} ...]

function login(u,p,callback){
    $.post('/login.php', {u:u, p:p}).done(function(){
       logout(callback);
    });
}

function logout(callback){
   // delete session cookies using javascript
   callback();
}

function main(){
  // recursive function to iterate in the data collection
  login(data[counter].u, data[counter].p, function(){
     if(counter++ < data.length){
        main();
     }
  });
}

Question

How do I do that using php curl? This is specifically about how to emulate sessions so that the "only member actions" can also be access after login.

How do I clear the session, if I don't have to use destroy sessions, in javascript you would just delete the session cookies stored in the browser. In curl php, how do I do that?

My attempt

$url = 'login.php';
$fields = array(
            'u' => urlencode('1'),
            'p' => urlencode('1')
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

As you can see, I tried 1 set of credentials. But beyond that, I do not know what to do.

  • 写回答

1条回答 默认 最新

  • douzhuan0309 2014-04-05 21:20
    关注

    How do I clear the session? In your php code you didn't create any session(i mean any cookie file). So you do not need to clear anything.

    But however, if you need to create session/cookie, then you have to use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE

    I have modified you code a bit too. Here it is:

    $fields = array(
        'u' => '1',
        'p' => '1'
    );
    
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
    
    // uncomment if you want to save cookie.
    // curl_setopt($ch, CURLOPT_COOKIEJAR, '/var/tmp/cookie.txt');
    // curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/tmp/cookie.txt');
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    // do some other processes
    
    // and then you can unlink('/var/tmp/cookie.txt') if you want
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上