21Dec/115
Using PHP and CURL to log in to a website
The other day I wanted to automate some downloading from a username and password secured website. I wrote a quick script and it is working like a dream, below is the CURL part of the code that does the logging in and download.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
$username = 'myuser'; $password = 'mypass'; $loginUrl = 'http://www.example.com/login/'; //init curl $ch = curl_init(); //Set the URL to work with curl_setopt($ch, CURLOPT_URL, $loginUrl); // ENABLE HTTP POST curl_setopt($ch, CURLOPT_POST, 1); //Set the post parameters curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password); //Handle cookies for the login curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); //Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL //not to print out the results of its query. //Instead, it will return the results as a string return value //from curl_exec() instead of the usual true/false. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //execute the request (the login) $store = curl_exec($ch); //the login is now done and you can continue to get the //protected content. //set the URL to the protected file curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/protected/download.zip'); //execute the request $content = curl_exec($ch); //save the data to disk file_put_contents('~/download.zip', $content); |

March 6th, 2013 - 08:53
How can I get cookie.txt?
March 6th, 2013 - 09:57
cookie.txt is created by cURL and used to store the login session info
April 20th, 2013 - 21:56
i need this for my android application to login in craigslist.org and post through my app,
i tried same to authenticate into craigslist.org but it is not working
can you please suggest me what to do..
April 22nd, 2013 - 09:24
You need to look at the websites source and see if you are passing al the required info and if the username and password fields have the same name as in the example.
May 20th, 2013 - 00:15
Hadn’t used curl before and was on my third day of trying web tweaks. Finally was about to give up and tried one last one, this one. It worked the first time. Perfect!