I'm new to using cURL and its hard to find good resources for it. What I'm trying to do is login to a remote site, by having curl do the login form and then send back that it was successful.
The code I have doesn't seem to work and only tries to show the main page of the site.
$username="mylogin@gmail.com";
$password="mypassword";
$url="http://www.myremotesite.com/index.php?page=login";
$cookie="cookie.txt";
$postdata = "email=".$username."&password=".$password;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
echo $result;
curl_close($ch);
What am I doing wrong. After this is working I want to redirect to another page and get content from my site.
I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.
Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc
I had same question and I found this answer on this website.
And I changed it just a little bit (the curl_close at last line)
I think this was what you were looking for.Am I right?
And one useful related question. About how to keep a session alive in cUrl: https://stackoverflow.com/a/13020494/2226796
Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :
View the source of the login page. Look for the
form
HTML tag. Within that tag is something that will look likeaction=
Use that value as$url
, not the URL of the form itself.Also, while you are there, verify the input boxes are named what you have them listed as.
For example, a basic login form will look similar to:
Using the above form as an example, change your value of
$url
to:Verify the values you have listed in
$postdata
:and it should work just fine.
This is how I solved this in ImpressPages: