How to log into a website using PHP+Javascript?

Asked

Viewed 499 times

0

I’m integrating three external systems that individually have their authentications. Each one makes a query of people, I have login and password of all, and none has Web Service. I’m a beginner in the subject of Httprequest, Urlconnection, etc... I’ve done a lot of research but I’m struggling. from what I understand I should use the request by filling a header, which I still don’t know the best way to find out. passing the authentication via cookie and thus staying logged in to make the query inside. With PHP+javascript, where do I start? What I found closer than I need is Login to a web site by the program

but I couldn’t apply, because I don’t understand how to do.

1 answer

1

Hello, the best way to do this is by using CURL

You can use this library to do this https://github.com/minkphp/MinkGoutteDriver It has several examples, and documentation on the site, I’ve used to do several projects

To do this with pure CURL you will have to do the following

1 - Perform a POST with login and password in the login url and capture the Cookie to use in the future for login

Example:

$ch = curl_init();                    // inicia o curl
$url = "http://www.site.com.br/post.php"; // Url para login
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");//seta onde guardar os cookies
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");//seta onde guardar os cookies
curl_setopt($ch, CURLOPT_POST, true);  // POST true
curl_setopt($ch, CURLOPT_POSTFIELDS, "login=admin&senha=1234"); // Defina o que vai enviar
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // quer retornar uma resposta ?
$result = curl_exec ($ch); // executa e salva a resposta em $result
$info = curl_getinfo($ch); // infos
curl_close ($ch); // fecha a conexão

//Extrai o cookie com base no login.
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}
$cookie_json = json_encode($cookies);
$cookie_json = json_decode($cookie_json);
$cookie_final = $cookie_json->{'SESSIONID'}; //salva em uma var o cookie

2 Perform the post with the cookie you just captured

$ch = curl_init('http://www.site.com.br/get_dados.php'); //Url para capturar algum dado que você deseja
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIE, 'SESSIONID={$cookie_final}');
$result = curl_exec
curl_close($ch);

echo $result;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.