How to log into a site using PHP + Javascript?

0

I am doing integration of 3 external systems that individually have their authentications. Each one does a people query, I have login and everyone password, and none has Web Service. I am a beginner in the subject of HTTPrequest, URLConnection, etc ... I have already researched the subject a lot but I am having difficulties. so I understand I should use the request by filling in a header, which I still do not know the best way to find out. passing the authentication via cookie and thus remain logged in to make the query inside. With PHP + javascript, where do I start? What I found closest to what I need is Login to a site on web by program

But I could not apply because I did not understand how to do it.

    
asked by anonymous 07.04.2017 / 15:53

1 answer

1

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

You can use this library to do this link It has several examples, and a documentation on the site, I used to do several projects

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

1 - Perform a POST with the login and password in the login url and capture the Cookie to use for future 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 Make 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;
    
11.10.2017 / 06:05