cURL and sessions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Kutulu
Forum Newbie
Posts: 1
Joined: Mon Jun 21, 2004 7:47 pm
Location: sweden
Contact:

cURL and sessions

Post by Kutulu »

I want to send a POST request to a URL which demands that you are logged in (a community) with a session.

Is there any way to do this, with cURL or anything else?

I need this to make a presentation generator :P
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

curl can easily do it..

using CURLOPT_POST_FIELDS or something.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

If remote server uses cookies to track session you could parse the response header for Set-Cookie: .*, store it to global variable and then use it on each request:

Code: Select all

//................
curl_setopt($cx, CURLOPT_COOKIE, $stored_cookie);
curl_exec($cx);
//..............
here is simple login using curl I used once:

Code: Select all

function login($login, $pass) {
  $cx = curl_init("http://www.example.com/login.php");
  $post_str = "username=$login&password=$pass&login=  login  ";
  curl_set_options($cx,
    array('returntransfer'=>true,
              'post'=>true,
              'postfields'=>$post_str,
           //   'nobody'=>true, // does not work for some weird reason
              'header'=>true
              )
          );
    $ret = curl_exec($cx);
    preg_match("/Set-Cookie: (.*);/i", $ret, $regs);
    return $regs[1];
}
$stored_cookie = login('test', 'test');
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

You will need both COOKIEFILE and COOKIEJAR...

Code: Select all

curl_setopt($ch, CURLOPT_COOKIEFILE, "/home/devel/cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/home/devel/cookie.txt");
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

there's no need to access the file (it's slow) for using just one cookie ;)
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

How do you know it's only one cookie? and how do you know that one cookie is not modified between page requests?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

I refer to default PHP session engine, where cookie containing sessid usually isn't modified between requests. Your approach is more generic, mine can be used in specific situations where speed is crucial.
Post Reply