sql >> Base de Datos >  >> RDS >> Mysql

Necesita ayuda para crear una secuencia de comandos de registro/inicio de sesión de usuario personalizada

Para este ejemplo, voy a omitir las declaraciones preparadas, pero deberá investigar un poco sobre la prevención de la inyección de SQL.

Primero necesita un formulario para que el usuario lo use para iniciar sesión. Aquí hay uno básico que estará en una página llamada NewUser.html:

<form action="AddUser.php" method="POST">
<p>Enter A Username: </p>
<input type="text" name="User" maxlength="20" size="10">
<br />
<p>Enter A Password: </p>
<input type="password" name="Password" maxlength="40" size="10">
<br />
<p>Enter Password Again: </p>
<input type="password" name="PasswordX2" maxlength="40" size="10">
<br />
<input type="submit" value="Create Account">
</form>

Por supuesto, puede agregar otros campos, como la dirección de correo electrónico, etc., pero lo mantendré simple.

Ahora vayamos a la página AddUser.php:

<?php

//Now let's grab our $_POST data from our form and assign them to variables...
$User = $_POST['User'];
$PW = $_POST['Password'];
$PW2 = $_POST['PasswordX2'];

//Check whether user put anything in the fields for user or passwords
if (!$User || !$PW || !$PW2) {
echo "You have not entered all the needed info. Please try again.";
exit();
}

//Check if passwords match
if ($PW <> $PW2) {
echo "Your passwords do not match. Please go back and try again.";
exit();
}

//Now we want to be good stewards of passwords and information so let's hash that password
$hash = password_hash($PW, PASSWORD_BCRYPT);

//Open your connection to database
$dbconnect-> blah blah(make your database connection here)....

//Now let's insert the new user into the database - remember do not do this without SQL-injection prevention. I'm just giving you the basics.
$sql = "INSERT INTO UsersTable (UserName, Password)
VALUES ('".$User."', '".$hash."')";

//Verify Successful Entry
if (mysqli_query($dbconnect,$sql)) {
echo "User Added Successfully";
} else {
echo "Error Creating User: " . mysqli_error($dbconnect);
}

echo "<br /><p>Please go to the main page to login now.</p>";
?>

Entonces, el usuario ahora ha sido creado, la contraseña ha sido codificada con sal e insertada en la base de datos ... en serio, no olvide la inyección de SQL.

Ahora tendrá un formulario que es muy similar al formulario NewUser.html para iniciar sesión, pero no requerirá que ingrese la contraseña dos veces. Digamos que el formulario de inicio de sesión envía al usuario a una página llamada login.php:

<?php
session_start(); //starts a session for tracking user on each page - this has to be on every page

//Let's get our variables from the POST data- will be identical to before most likely
$User = $_POST['User'];
$PW = $_POST['Password'];

//Open your connection to database
$dbconnect-> blah blah(make your database connection here)....

//Let's see if the username and password matches what we have in the database
$sql = "SELECT UsersTable.UserName, UsersTable.Password
FROM UsersTable
WHERE UsersTable.UserName = '$User'";
$result = $dbconnect->query($sql);

//Let's get the hashed password that corresponds to that username
$row = $result->fetch_assoc();
$HashedPassword = $row['Password'];

//Let's verify the password is correct
if (password_verify($PW, $HashedPassword))
{

//if it is correct(true) this will now happen
$_SESSION['verified_user'] = $User; //registers user by storing it in a SESSION
}
else {
echo "Login failed. Try again.";
exit();
}
?>

Solo un consejo, si desea agregar niveles de acceso, puede almacenar un lugar en la base de datos con un número de acceso (por ejemplo, 1, 2, 3) y luego, al iniciar sesión correctamente, asignaría otro $_SESSION que represente su nivel de acceso y les da acceso a ciertas secciones que usted permite.

Ahora, cuando naveguen a otras páginas de su sitio, su sesión se verificará así:

EjemploPágina.php

<?php
session_start();

if (isset($_SESSION['verified_user'])) {
//User is verified and whatever is here will be visible and happen- YAY!
}
else {
echo "You are not logged in and cannot see this page.";
}
?>

Simplemente acostúmbrese a iniciar una sesión en cada página a la que solo puedan acceder aquellos que hayan iniciado sesión. Las sesiones se recuerdan de una página a otra.

No olvide darles una página de cierre de sesión que destruirá la sesión:logout.php

<?php
session_start();

unset($_SESSION['verified_user']);
session_destroy();
echo "You are logged out.";
?>