Set a cookie via CURL (php)

Is is possible to create a cookie / session via cURL? I’m sending login data via cURL to a wordpress file and if the data are correct I want to login the user. Is there a way to do that? My curl file looks like this:

    $url = 'http://www.domain.de/blog/wordpress-dosomething.php?username=[username]&password=[password]&rememberMe=[rememberMe]'; 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $rsp = curl_exec($ch);
    curl_close($ch);

And my wordpress file looks like this:

Read More
$username = $_GET['username'];
$password = $_GET['password'];
//login the user
$user = wp_signon( array('user_login' => $username, 'user_password' => $password, 'remember' => $remember), false );
if ( is_wp_error($user) )
  //error...

If I test this by calling the wordpress file manually, this works and I’m logged in to wordpress. But via curl it doesn’t work, even though there is no error, so how can I make this work? Can I somehow… I don’t know… catch the session/cookie set by my script and manually set it in my curl Script file?

Thanks in advance.

Related posts

2 comments

  1. You could set cookie through the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options of curl in PHP. Example:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFilePath);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFilePath);
    $rsp = curl_exec($ch);
    curl_close($ch);
    

    Then the cookie content will be automatically saved in the $cookieFilePath, which is a local file path.

  2. Add COOKIEFILE and COOKIEJAR as option and a text file named cookie.txt in your aplication directory

    $cookie_file=realpath('cookie.txt');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    $rsp = curl_exec($ch);
    curl_close($ch);
    

    hope this will help

Comments are closed.