Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Include file that contains the connection to MySQL ($conAdmin)
- require_once("mysql.php");
- // If there's no input (empty login field), return to the login page
- if (!isset($_POST["login"])) { header("Location:login.php"); exit; }
- // Set $login and $password vars to field content (less to type later :P)
- $login = $_POST["login"];
- $password = $_POST["password"];
- // If connection to the database cannot be established, return the error and quit...
- if ($conAdmin->connect_errno) { echo $conAdmin->connect_errno; exit; }
- // ...otherwise continue
- try {
- // This is where I check does the user exist
- if ($stmt = $conAdmin->prepare("SELECT * FROM users WHERE login = ?")) {
- // I add user input to the query above (prepared statement ofc, you can't trust it)
- $stmt->bind_param("s", $login);
- // execute the query...
- $stmt->execute();
- // ...and get its result...
- $result = $stmt->get_result();
- // ...more specifically, the number of records returned (either 0 or 1)
- $rows = mysqli_num_rows($result);
- // if it's 0 -- user does not exist
- if ($rows == 0) {
- // if user doesn't exist, throw an error (it'll be caught at line 54)
- throw new Exception('User does not exist.');
- } // in theory, there should be elseif ($rows == 1), but it *must* be either 0 or 1 so \_(^^)_/
- // move the mysql result (so user's id, login, password and salt) to an numeric array
- $mysqlData = $result->fetch_array(MYSQLI_NUM);
- // and sort them into readable vars
- // yup, i know i could have used assoc array, but tbh i can't event remember when i wrote this code xd
- $userId = $mysqlData[0];
- $mysqlPassword = $mysqlData[2];
- $salt = $mysqlData[3];
- // no idea if you know what salting a password is, but doesn't matter here
- // im basically making sure the password is correct at this point
- $newHashed = hash("sha256", $password.$salt);
- if ($newHashed != $mysqlPassword) {
- // if not, throw an error that's -- again -- caught at line 54
- throw new Exception('The password is incorrect!');
- }
- // if the password is correct, the user should get logged in
- // code below is only needed for websites, so that's the end of an example :P
- session_start();
- $_SESSION['id'] = $userId;
- $_SESSION['login'] = $login;
- header("Location:index.php");
- $stmt->close();
- } else {
- echo "Prepare failed: (" . $conAdmin->errno . ") " . $conAdmin->error;
- }
- } catch (Exception $e) {
- echo '<b>An error occured: </b>' . $e->getMessage();
- }
- $conAdmin->close();
- include('login.php');
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement