Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- session_set_cookie_params(0, '/', 'localhost', false, true);
- session_start();
- // create form token
- $_SESSION['token_login'] = bin2hex(random_bytes(32));
- ?>
- <!-- THE FORM -->
- <form class="login" method="post" name="login" id="login-form">
- <input type="text" class="form-control" name="username" id="username" placeholder="Username">
- <input type="password" class="form-control " name="password" id="password" placeholder="Password">
- <input type="hidden" name="token" id="token" value="<?php echo $_SESSION['token_login']; ?>">
- <input type="text" name="user" id="user" class="hidden" />
- <a href="javascript:void(0)" onclick="sendLogin()" class="btn btn-success btn-block">Entrar</a>
- </form>
- <div class="msgs"></div>
- <!-- the ajax call -->
- <script>
- function sendLogin() {
- var msgs = $('.msgs');
- var data = $('#login-form').serialize();
- var url = 'ajax/login.ajax.php';
- $.ajax({
- url: url,
- data: data,
- type: 'POST',
- success: function(response) {
- var json = $.parseJSON(response);
- $('input').removeClass('is-invalid');
- var fields = json.fields;
- for(var i=0; i<fields.length; i++) {
- $('#'+fields[i]).addClass('is-invalid');
- }
- msgs.html('<p class="error-msgs">'+json.msg+'</p>');
- $('#token').val(json.token);
- if(json.type == 'success') {
- msgs.html('<p class="success">Redirecting...</p>');
- $(location).attr("href","dashboard.php");
- }
- }
- });
- }
- </script>
- <?php
- // THE LOGIN.AJAX.PHP PAGE
- session_start();
- if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST)) {
- $username = clearTags($_POST['username']);
- $password = clearTags($_POST['password']);
- $token = clearTags($_POST['token']);
- $user = clearTags($_POST['user']);
- $error = false;
- $msg = '';
- $fields = [];
- $type = '';
- if(strlen($username) < 3) {
- $error = true;
- array_push($fields, 'username');
- }
- if(strlen($password) < 3) {
- $error = true;
- array_push($fields, 'password');
- }
- if($token !== $_SESSION['token_login']) {
- $error = true;
- array_push($fields, 'token');
- }
- if(strlen($user) !== 0) {
- $error = true;
- array_push($fields, 'user');
- }
- if($error) {
- $msg = 'Existem erros no formulário!';
- $type = 'error';
- }
- else {
- }
- // generate new token to send to form
- $_SESSION['token_login'] = bin2hex(random_bytes(32));
- // prepare response to send as json
- $response = [];
- $response['type'] = $type;
- $response['fields'] = $fields;
- $response['msg'] = $msg;
- $response['token'] = $_SESSION['token_login'];
- echo json_encode($response);
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement