使用 cURL 登录并保存会话

0 php session curl

索引.php

<?php
if($_POST) {
    $url = 'http://127.0.0.1/login.php';
    $socks = '127.0.0.1:9999';
    $fields = 'password=' . $_POST['captcha'] . '';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
    //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
    //curl_setopt($ch, CURLOPT_PROXY, $socks);
    //curl_setopt($ch, CURLOPT_INTERFACE, 'eth0:12');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3600);

    $result = curl_exec($ch);

    curl_close($ch);
}
?>
<form action="" method="POST">
    Password <input type="text" name="password" value="" />
    <input type="submit" value="Login" />
</form>
Run Code Online (Sandbox Code Playgroud)

登录.php

<?php
session_start();

$_SESSION["TestSession"] = 1;
setcookie("TestCookie", 1, time() + 3600);

if($_POST) {
    file_put_contents("login.txt", serialize($_POST));
}

echo 'OK';
?>
Run Code Online (Sandbox Code Playgroud)

在我运行index.php并使用我的密码提交表单后,它被保存到login.txtcookie.txt我没有TestCookie或已TestSession保存。

我将感谢任何帮助,因为我真的不明白问题出在哪里。

Man*_*pka 5

这就是我在 ImpressPages 中解决此问题的方法:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}
Run Code Online (Sandbox Code Playgroud)