cURL / Mailing Lists / curl-and-php / Single Mail

curl-and-php

Re: How do I get POST working? Please.

From: Daniel Stenberg <daniel_at_haxx.se>
Date: Thu, 23 Oct 2003 07:57:10 +0200 (CEST)

On Wed, 22 Oct 2003, ErAzeR wrote:

> I want to login on pages using curl, which doesn't seem to work for me. For
> example I tried to log into fileforum and display the page which loads right
> after you have logged in. I used this code:

> <?
> $url = 'http://www.betanews.com/login.php3';
> $postfields = 'username=just_testing&password=just_testing'; //Login and password works for real, so you can try it out.

This doesn't set the name and value of the submit button. It seems you should
add "&submit=Login%20now" to the string above.

> $ch = curl_init();
>
> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
>
> curl_setopt($ch, CURLOPT_URL, $url);

AFAIR, you can give the URL to the curl_init() function, like this:

  $ch = curl_init($url);

> curl_setopt($ch, CURLOPT_POST, 1);
> curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
> curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

You're setting CURLOPT_RETURNTRANSFER twice.

> $return = curl_exec($ch);

In order to debug operations such as this, you *should* use CURLOPT_VERBOSE
and you should carefully check the data and headers curl sends and receives.

Like in this case, I bet the site might send you a Location: header that you
haven't told curl to follow. Try CURLOPT_FOLLOWLOCATION.

Also, it is very common for sites to set a cookie on a successful login, so
that they can track your session properly. Your functions above does not deal
with cookies and thus it might fail (even if it would follow the Location:).

Try CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR to enable cookies.

Some sites also check the referer or user-agent fields, but fix the above
first.

> Actually I dont get the POST function to work on any page?

I suggest you always start out by doing things like this with the curl command
line tool. I find that a lot easier and quicker to prototype things like this.
When you know what command lines that work, then you convert them into
PHP-code. IMHO the best approach.

> What is missing?

An understanding of the fundamentals that HTTP and sites use for this kind of
stuff.

> It would be nice with a working example of php code which uses CURL to login
> to a page, and displaying that page.

We suffer from a lack of good and useful (working) PHP examples that use the
CURL binding. That's one of the reasons for the recently announced
competition:

        http://curl.haxx.se/competition.html

-- 
 Daniel Stenberg -- curl: been grokking URLs since 1998
-------------------------------------------------------
This SF.net email is sponsored by: The SF.net Donation Program.
Do you like what SourceForge.net is doing for the Open
Source Community?  Make a contribution, and help us add new
features and functionality. Click here: http://sourceforge.net/donate/
Received on 2003-10-23