Login Login

-1

I wish only that I had access to dashboard of my page ( link ), I created a login page but I do not know such as allowing only my access.

I would like to use a COOKIE for this, created only when my email and password were entered. Otherwise, the user would be redirected back to the login page.

Here is the code for my form:

<form class="loginform">
    <input type="text" style="background-color: #fff; border-radius: 3px; padding: 17px 20px; border: none; width: 220px; margin-top: 10px;" name="email" class="mail" placeholder="E-Mail Address" required="">
    <input type="password" style="background-color: #fff; border-radius: 3px; padding: 17px 20px; border: none; width: 220px; margin-top: 10px;" name="password" class="password" placeholder="Password" required="">
    <input style="padding: 15px 50px; margin-left: 60px;" type="submit" class="login" onclick="alert('Login failed. Check if you typed something wrong or used capital letters in your password. You may have left a field blank.')" value="Login">
</form>
    
asked by anonymous 01.05.2015 / 03:35

2 answers

7

Good friend, first what you need to understand is what a cookie is, come on.

What is a cookie? Technically speaking, a cookie is a set of information that is stored on the user's machine, so that he can, for example, add products to a shopping cart, enter your login and password only once and be reminded for a while, this is because each cookie has an expiration date.

I recommend reading this article: Differences between Cookies and Sessions you requested a cookie, but it is important to know what a session is as well.

So by putting the focus on your system, the cookie will not ONLY access the system, but it will be created with the information you set and at a later time, allow access without you having to type your email and password again, remembering, only on the same machine.

As the code you have so far is just html, I have given myself the freedom to create the codes javascript/jquery and php .

First I got all the css inline from your form and put it inside the <style> tag (for better visualization and organization). With this, the code of your form looks like this:

<form id="login-form" class="loginform">
    <input type="text" name="email" id="email" class="input-field" placeholder="E-Mail Address" required>
    <input type="password" name="password" id="password" class="input-field" placeholder="Password" required>
    <input type="submit" class="input-submit" value="Login">
</form>

Well, that's better, is not it? Now your css code:

<style>
    .input-field {
        background-color: #fff;
        border-radius: 3px;
        padding: 17px 20px;
        border: none;
        width: 220px;
        margin-top: 10px;
    }
    .input-submit {
        padding: 15px 50px;
        margin-left: 60px;
    }
</style>

Let's go to our code javascript , I usually send my forms via ajax (in this example I'll do so), but using it is not necessary. For this you need to have jQuery included in your site .

<script>
    $(document).ready(function() {
        $('#login-form').submit(function() {
            // Capturamos o evento de submit do formulário
            // e impedimos que ele sejá concluído.
            e.preventDefault();

            var mail = $('#email').val(),
                pass = $('#password').val();

            // Coloque as validações dos campos aqui, se houver.

            $.ajax({
                url: 'sua_pagina.php',  // Essa página receberá os dados do javascript e fará as validações e criará o cookie
                data: $('#login-form').serialize()
            })
            .done(function(data) {
                if (data == 'logged') {
                    windows.location.href = 'dashboard.php';
                } else if (data == 'login failed') {
                    alert('Email ou senha incorretos.');
                }
            })
            .fail(function(data) {
                console.log(data)
            });
        });
    });
</script>

Explaining: We will send the data of your form to the page sua_pagina.php , it will receive the data, make the validations and consequently create the cookie or else, return fill error. The form is being sent by POST .

Now, follow the code of sua_pagina.php :

<?php

$mail = $_POST["email"];
$pass = $_POST["password"];

// Parte de validações dos valores
// [...]

// Parte em que você recupera os valores corretos do banco
// Como você não disse se tem uma tabela para usuário ou não
// e sim "exatamente meu email e senha" vamos declarar no código mesmo
// porém NUNCA FAÇA ISSO!!
$meu_email   = "[email protected]";
$minha_senha = "asdfasdf123123asdsd123123";

// Recomendo utilizar hash para armazenar e verificar sua senha
// http://php.net/manual/pt_BR/function.password-hash.php
if ( $mail == $meu_email && $pass == $minha_senha ) {

    // A função time() retorna a hora atual medida
    // no número de segundos desde 1 de janeiro de 1970 (http://php.net/manual/pt_BR/function.time.php)
    // Nesse caso, definimos o cookie com um prazo de expiração de 30 dias.
    // Documentação da função setcookie(): http://php.net/setcookie
    setcookie( "email", $mail, ( time() + (30 * 24 * 3600) ) );
    setcookie( "pass", $pass, ( time() + (30 * 24 * 3600) ) );

    echo "logged";
    exit();
} else {
    echo "login failed";
    exit();
}

If the data entered in the form is correct, we will be redirected to the dashboard.php page, and at the beginning of the code and all the pages you want to protect we should verify that the cookie exists:

<?php
    if ( !isset($_COOKIE["email"]) && !isset($_COOKIE["pass"]) ) {
        header("Location: signin.php");
    }
    
01.05.2015 / 04:48
1

An alternative and simpler way (I think) would be to use PHP session:

session_start();
if((!isset($_SESSION['email']) == true) and (!isset($_SESSION['pass']) == true)){
        require_once 'components/modals/login-modal.php';
        require_once 'components/modals/create-account-modal.php';
    }else{
        require_once 'components/modals/logout-modal.php';
    }

Explaining: I split my page into small php files (with pure HTML elements) and check if the user is logged in yes the page will be composed with a logout button if not with login and registration buttons.

    
01.05.2015 / 15:25