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");
}
Can you put the html code of your form? It will make things easier.
– Eduardo Silva
I put below in an answer to the question.
– Hugo Marcelo
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.
– Eduardo Silva
Sorry. I’m new around here :/
– Hugo Marcelo
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.
– Eduardo Silva
I fixed the question :) Thank you. I didn’t know that.
– Hugo Marcelo