Curl login, then redirect client to logged in page


I have a cURL script, which logs in to a site with hardcoded login details. This is OK, and it’s working.

Also I want to redirect the client to the logged in page, logged in. The target page is not on my server and I don’t have access to the code.
How can I do that?


From your description, you can’t do that. The client will need to know the hardcoded login details, or the target page will need some form of special auth(entication/orisation) setup.

One way that could work (provided some conditions are met):
When you are logged in the remote site sets a session cookie - Typically PHPSESSID. By default PHP allows sessions to be sent either using cookies or via GET. So what you need, to do is to redirect user to remote page:{whatever_the_cookie_value_was_that_you_received_through_curl}

This might work. But only if remote site does not take IP address into account and allows session id to be passed around through GET.


How can I get the returned PHPSESSID from cURL?

The -v command line switch among other things turns on display of headers that you send and what server responds. For instance, if I type:
curl -v
I get this:

  • About to connect() to port 80 (#0)
  • Trying… connected
  • Connected to ( port 80 (#0)
    > GET / HTTP/1.1
    > User-Agent: curl/7.18.2 (i686-pc-linux-gnu) libcurl/7.18.2 OpenSSL/0.9.8h zlib/1.2.3
    > Host:
    > Accept: /
    < HTTP/1.1 200 OK
    < Date: Fri, 05 Dec 2008 11:18:26 GMT
    < Server: Apache/2.0.46 (Red Hat)
    < X-Powered-By: PHP/4.3.11
    < Cache-Control: private, max-age=600
    < Set-Cookie: SID=9f68900d0a7088b1a252650e2b78b319; path=/
    < Set-Cookie: SPabc=a; expires=Sat, 05 Dec 2009 11:18:26 GMT; path=/
    < Transfer-Encoding: chunked
    < Content-Type: text/html
    … the usual content follows

and how that works with PHP curl library?

I use this

$ch = @curl_init();
@curl_setopt($ch, CURLOPT_URL,$loginURL);
@curl_setopt($ch, CURLOPT_POST, 1);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_REFERER, $reffer);
@curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
@curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = @curl_exec ($ch);
@curl_close ($ch);

From the documentation:

CURLOPT_HEADER TRUE to include the header in the output.

I gather, that you have to use:
curl_setopt($ch, CURLOPT_HEADER, true);