I am trying to login to a web site through cURL in PHP to later web scraping the resulting page when logging in. I am using the following code:
<?php
$url = 'URL en la que quiero logearme';
$ch = curl_init();
$parametros_post = 'ips_username='.urlencode("nombre de Usuario").'&ips_password='.urlencode("contraseña").'&rememberMe='.urlencode("1").'&anonymous='.urlencode("1");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0');
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept-Language: es-es,en"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parametros_post);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
//Guardar página
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
//Comprobar si ha hecho login en la página
echo $result;
?>
Clarifications:
- As
$urlI used what appears on the page within the "action" field of<form>login. - In the variable
$parametros_postI have included all fields<input>of the form that had a "name" tag with the value of my user or failing that with the value that appeared in its "value" tag. - The submit button did not contain a "name" tag, so I did not include it in the variable
$parametros_post(although it did contain type, class, value and tabIndex, I do not know if it will influence anything). - I am using a localhost through WampServer with Apache and PHP 5.4.3.
- Cookies must be incorrectly configured because when I start the .php file on my localhost I get
Notice: Undefined variable: cookie_file. - When opening the .php file in localhost, in the web page I'm trying to log in to, a message appears saying
Sorry, you don't have permission for that. We encountered a problem precessing your login request, that is, when processing the php request instead of sending me to the home page and logged in they send me to an error page, I guess because I do not have cookies properly set up. - The page I'm trying to log in to is https, in case it works or changes something.