The following information is pretty important (and specific to Amazon.com) (remember, this could change at any time and make this code not work.) The idea is that we are emulating the exact same webform that a browser would submit when an actual user is loggin in. The pieces of the form are the following:
This can either be combined together to a string (like email=jjg@go.com&password=mypass&….) or as an array. CURL handles both just fine, and because it is “prettier” to have an array, that is the form I chose.
After this, we need to actually do the submitting. Logging in is really just authenticating to the server and receiving a cookie for storage on your computer. So we submit the form, and tell CURL to store a cookie in a file we choose. Then, if we tell CURL to read from that cookie file when accessing Amazon.com later, it will act as though we’ve logged in.
Here is the code for submitting with comments:
<?php
// Initialize the curl object
$cr = curl_init(’https://www.amazon.com/gp/flex/sign-in/select.html’);
curl_setopt($cr, CURLOPT_RETURNTRANSFER, true); // Get returned value as string (don’t put to screen)
curl_setopt($cr, CURLOPT_USERAGENT, $_SERVER[’HTTP_USER_AGENT’]); // Spoof the user-agent to be the browser that the user is on (and accessing the php script)
curl_setopt($cr, CURLOPT_COOKIEJAR, ‘cookie.txt’); // Use cookie.txt for STORING cookies
curl_setopt($cr, CURLOPT_POST, true); // Tell curl that we are posting data
curl_setopt($cr, CURLOPT_POSTFIELDS, $data); // Post the data in the array above
$output = curl_exec($cr); // Execute!
echo $output; // Spit out what we found
curl_close($cr); // Free the memory
?>
If it worked successfully, then the following code (which just accesses Amazon’s homepage) will access the homepage of a logged in user. (It should say your name, etc)
<?php
$cr = curl_init(’http://www.amazon.com/gp/homepage.html’);
curl_setopt($cr, CURLOPT_RETURNTRANSFER, true); // Get returned value as string (don’t put to screen)
curl_setopt($cr, CURLOPT_USERAGENT, $_SERVER[’HTTP_USER_AGENT’]); // Spoof the user agent
curl_setopt($cr, CURLOPT_COOKIEFILE, ‘cookie.txt’); // Use cookie.txt for READING cookies
$output = curl_exec($cr);
curl_close($cr);
echo $output;
?>
If everything has gone to plan, then you will have logged in and the cookie (in cookie.txt) will give you access as if you had logged in normally on Amazon.com
I hope this helps someone who is stuck with Amazon! It gave me a bit of troule, but I worked it out eventually.