Login

Asked

Viewed 125 times

-1

I wish only I had access to dashboard of my page (http://hugovales.esy.es/singin), I created a login page but I don’t know how to only allow 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 again to the login page.

Here’s the code to 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>
  • 1

    Can you put the html code of your form? It will make things easier.

  • I put below in an answer to the question.

  • 1

    Friend, edit your question and put the code in it, not in an answer. I need your form code to see the name of the fields, etc.

  • Sorry. I’m new around here :/

  • 1

    Take it easy, Hugo! No problem, I’m just telling you this so your question is well evaluated and to make it easier to read, the way it is, your question can be closed or you get negative points.

  • I fixed the question :) Thank you. I didn’t know that.

Show 1 more comment

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 it can, for example, add products to a shopping cart, enter your login and password only once and be remembered for a while, because each cookie has an expiration date.

I recommend reading this matter: Differences between Cookies and Sessions, you asked for a cookie, but it’s important to know what a session is too.

Then, by focusing on your system, the cookie will not ONLY access the system, but will be created with the information you set and at a future time, allow access without you having to enter your email and password again, remembering, only on the same machine.

Since the code you have so far is only html, I gave myself the freedom to create the codes javascript/jquery and php.

First I caught all the css inline of your form and placed inside the tag <style> (for better visualization and organization). With this, the code of your form was 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>

Much better, no? 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 always send my forms by ajax (in this example I will do so), but the use of it is not necessary. For this you need to have included in your website the jQuery.

<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 your form data to the page sua_pagina.php, it will receive the data, make the validations and consequently create the cookie or 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/en/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/en/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 page dashboard.php, and at the beginning of her code and all the pages you want to protect we shall check if the cookie exists:

<?php
    if ( !isset($_COOKIE["email"]) && !isset($_COOKIE["pass"]) ) {
        header("Location: signin.php");
    }
  • Thank you. I will test. I hope it works. I thank you for taking the time to help me.

  • It didn’t work, thanks anyway. I followed all the steps, but I couldn’t. I used Jquery, and PHP, all right, but I couldn’t :\

  • 1

    The @Eduardo Silva Reply is with everything you need, can explain what happened that did not work?

  • I used the code, but when I log in it didn’t work. Still, I thank you.

1

An alternative and simpler way (I think) would be to use PHP Séssion:

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 divided my page into small php files (with pure HTML elements) and check if the user is logged in if yes the page will be composed with a logout button if not with login and registration buttons.

Browser other questions tagged

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