【问题标题】:How to do curl in php and save sessions, and eventually use a session variable如何在php中进行curl并保存会话,并最终使用会话变量
【发布时间】:2014-04-05 18:41:43
【问题描述】:

我试图通过在 google chrome 控制台中粘贴一堆代码来模拟使用 javascript 的大规模登录。

这些是我基本上做的:

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();
     }
  });
}

问题

如何使用 php curl 做到这一点?这特别是关于如何模拟会话,以便在登录后也可以访问“唯一成员操作”。

如何清除会话,如果我不必使用销毁会话,在 javascript 中您只需删除存储在浏览器中的会话 cookie。在 curl php 中,我该怎么做?

我的尝试

$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);

如您所见,我尝试了一组凭据。但除此之外,我不知道该怎么办。

【问题讨论】:

  • 你试过用php做些什么吗?
  • 啊,是的,我应该发帖吗?

标签: javascript php session curl


【解决方案1】:

How do I clear the session? 在您的 php 代码中,您没有创建任何会话(我的意思是任何 cookie 文件)。所以你不需要清除任何东西。

但是,如果您需要创建会话/cookie,则必须使用CURLOPT_COOKIEJARCURLOPT_COOKIEFILE

我也稍微修改了你的代码。这里是:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    相关资源
    最近更新 更多