usuarios usuario usando sistema sesiones sesion seguro registro inicio descargar datos control con completo buscar boton avanzado autenticaciĆ³n administrador php mysql sql forms login

usuario - sistema de login php y mysql avanzado



No puedo obtener mi formulario de inicio de sesiĆ³n para conectarse a interactuar correctamente con la base de datos mySQL (1)

Esta respuesta es para hash, password_hash () y password_verify () . Para ambos, mysqli y pdo. El enlace en la parte inferior tiene enlaces adicionales y algún lenguaje sobre sales y similares.

Es crucial no utilizar datos proporcionados por el usuario directamente con selecciones e inserciones. Más bien, enlace los parámetros y llame a las declaraciones preparadas para evitar los ataques de inyección sql . Las contraseñas nunca deben guardarse en claro (texto claro) en las bases de datos. Por el contrario, deben enviarse a través de hash de un solo sentido.

También tenga en cuenta. Esto muestra el hash de registro y la verificación de inicio de sesión. No es una funcionalidad completa . Estoy tratando de bloquear Hock en codecanyon por diez dólares ... de modo que muestra un nuevo registro de una dirección de correo electrónico (el inicio de sesión) ya existe, hace actualizaciones, eso sí. En ese caso, la inserción simplemente fallará debido a la clave única establecida en el db. Dejo eso a usted, el lector, para hacer la búsqueda y decir ''correo electrónico ya registrado''.

Esquema

CREATE TABLE `user_accounts2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`), unique key(email) -- that better be the case ) ENGINE=InnoDB;

Después de ejecutar register.php y guardar un usuario, los datos podrían verse así:

select * from user_accounts2; +----+-----------+--------------------------------------------------------------+ | id | email | password | +----+-----------+--------------------------------------------------------------+ | 1 | [email protected] | $2y$10$U6.WR.tiOIYNGDWddfT7kevJU8uiz8KAkdxXpda9e1xuplhC/eTJS | +----+-----------+--------------------------------------------------------------+

sección mysqli primero

register.php

<?php mysqli_report(MYSQLI_REPORT_ALL); error_reporting(E_ALL); // report all PHP errors ini_set("display_errors", 1); // display them session_start(); if(isset($_SESSION[''userid''])!="") { // you are already logged in as session has been set header("Location: safe.php"); // note that this re-direct will at the top of that page // ... and there to verify the session state so no tricks can be performed // no tricks and gimmicks } if(isset($_POST[''register''])) { $email = $_POST[''email'']; $ctPassword = $_POST[''password'']; // cleartext password from user $hp=password_hash($ctPassword,PASSWORD_DEFAULT); // hashed password using cleartext one // pretend the following is locked in a vault and loaded but hard coded here $host="yourhostname"; $dbname="dbname"; $user="dbuser"; $pwd="password"; $port=3306; // comes along for the ride so I don''t need to look up param order below // end pretend try { $mysqli= new mysqli($host, $user, $pwd, $dbname,$port); if ($mysqli->connect_error) { die(''Connect Error ('' . $mysqli->connect_errno . '') '' . $mysqli->connect_error); } //echo "I am connected and feel happy.<br/>"; $query = "INSERT INTO user_accounts2(email,password) VALUES (?,?)"; $stmt = $mysqli->prepare($query); // note the 2 s''s below, s is for string $stmt->bind_param("ss", $email,$hp); // never ever use non-sanitized user supplied data. Bind it $stmt->execute(); // password is saved as hashed, will be verified on login page with password_verify() $iLastInsertId=$mysqli->insert_id; // do something special with this (or not) // redirect to some login page (for now you just sit here) $stmt->close(); $mysqli->close(); } catch (mysqli_sql_exception $e) { throw $e; } } ?> <html> <head> <title>Register new user</title> </head> <body> <div id="reg-form"> <form method="post"> <table> <tr> <td><input type="email" name="email" placeholder="Email" required /></td> </tr> <tr> <td><input type="password" name="password" placeholder="Password" required /></td> </tr> <tr> <td><button type="submit" name="register">Register</button></td> </tr> <tr> <td><a href="index.php">Normal Login In Here</a></td> </tr> </table> </form> </div> </body> </html>

login.php

<?php mysqli_report(MYSQLI_REPORT_ALL); error_reporting(E_ALL); // report all PHP errors ini_set("display_errors", 1); // display them session_start(); if(isset($_SESSION[''userid''])!="") { // you are already logged in as session has been set header("Location: safe.php"); // note that this re-direct will at the top of that page // ... and there to verify the session state so no tricks can be performed // no tricks and gimmicks } if(isset($_POST[''login''])) { $email = $_POST[''email'']; $ctPassword = $_POST[''password'']; // cleartext password from user // pretend the following is locked in a vault and loaded but hard coded here $host="yourhostname"; $dbname="dbname"; $user="dbuser"; $pwd="password"; $port=3306; // comes along for the ride so I don''t need to look up param order below // end pretend try { $mysqli= new mysqli($host, $user, $pwd, $dbname,$port); if ($mysqli->connect_error) { die(''Connect Error ('' . $mysqli->connect_errno . '') '' . $mysqli->connect_error); } //echo "I am connected and feel happy.<br/>"; $query = "select id,email,password from user_accounts2 where email=?"; $stmt = $mysqli->prepare($query); // note the "s" below, s is for string $stmt->bind_param("s", $email); // never ever use non-sanitized user supplied data. Bind it $stmt->execute(); $result = $stmt->get_result(); if ($row = $result->fetch_array(MYSQLI_ASSOC)) { $dbHashedPassword=$row[''password'']; if (password_verify($ctPassword,$dbHashedPassword)) { echo "right, userid="; $_SESSION[''userid'']=$row[''id'']; echo $_SESSION[''userid'']; // redirect to safe.php (note safeguards verbiage at top of this file about it) } else { echo "wrong"; // could be overkill here, but in logout.php // clear the $_SESSION[''userid''] } } else { echo ''no such record''; } // remember, there is no iterating through rows, since there is 1 or 0 (email has a unique key) // also, hashes are one-way functions in the db. Once you hash and do the insert // there is pretty much no coming back to cleartext from the db with it. you just VERIFY it $stmt->close(); $mysqli->close(); } catch (mysqli_sql_exception $e) { throw $e; } } ?> <html> <head> <title>Login</title> </head> <body> <div id="reg-form"> <form method="post"> <table> <tr> <td><input type="email" name="email" placeholder="Email" required /></td> </tr> <tr> <td><input type="password" name="password" placeholder="Password" required /></td> </tr> <tr> <td><button type="submit" name="login">Login</button></td> </tr> </table> </form> </div> </body> </html>

sección de pdo a continuación

Cuando tenga tiempo, probablemente mañana, pero por ahora te señalo esta Respuesta mía .

Lo que me gustaría que ocurra es que el usuario inicie sesión con un nombre de usuario y contraseña, y si los datos coinciden con el del databse. Cuando lo intento, no aparece ningún error, pero no funciona. Estoy usando html y php en dreamweaver, y WAM con phpMyAdmin. Incluiré tanto el documento del formulario como el documento php que lo acompaña:

loginpage.php

<?php include(''login.php''); // Includes Login Script if(isset($_SESSION[''login_user''])){ header("location: index.php"); } ?> <table width="15px" border="0"> <form form action=''login.php'' method=''POST''> <tr> <td>Username</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" /></td> </tr> <tr> <td><input type="submit" name="submit" value="submit"/></td> </tr> </form>

login.php

<html> <head> <title>Login</title> </head> <body> <?php session_start(); // Starting Session $error=''''; // Variable To Store Error Message if (isset($_POST[''submit''])) { if (empty($_POST[''username'']) || empty($_POST[''password''])) { $error = "Username or Password is invalid"; } else { // Define $username and $password $username=$_POST[''username'']; $password=$_POST[''password'']; // Establishing Connection with Server by passing server_name, user_id and password as a parameter $hostname= "localhost"; $database = "boost"; $username = "root"; $password = ""; $localhost = mysqli_connect($hostname, $username, $password, $database); if(mysqli_connect_errno()) { die("Connection Failed".mysqli_error()); } // SQL query to fetch information of registerd users and finds user match. $sql = "SELECT * FROM `users`"; $query = mysqli_query($localhost,$sql); if(!$query) { die("Query Failed".mysqli_error($localhost)); } $rows = mysqli_num_rows($query); if ($rows == 1) { $_SESSION[''login_user'']=$username; // Initializing Session echo "You are now logged on!"; } else { $error = "Username or Password is invalid"; } mysqli_close($localhost); // Closing Connection } } ?> </body> </html>