简体   繁体   English

如何在php中卷曲并保存会话,并最终使用会话变量

[英]How to do curl in php and save sessions, and eventually use a session variable

I have tried to simulate mass login using javascript, by pasting a bunch of codes in the google chrome console. 我试图通过使用JavaScript通过在Google Chrome控制台中粘贴一堆代码来模拟大规模登录。

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? 我该如何使用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. 如何清除会话,如果我不必使用destroy会话,则在javascript中,您只需删除存储在浏览器中的会话cookie。 In curl php, how do I do that? 在curl php中,我该怎么做?

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. 如您所见,我尝试了1套凭据。 But beyond that, I do not know what to do. 但是除此之外,我不知道该怎么办。

How do I clear the session? In your php code you didn't create any session(i mean any cookie file). 在您的PHP代码中,您没有创建任何会话(我的意思是任何cookie文件)。 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 但是,如果您需要创建会话/ cookie,则必须使用CURLOPT_COOKIEJARCURLOPT_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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM