Jump to content

Mayube

Member
  • Posts

    1
  • Joined

  • Last visited

Awards

This user doesn't have any awards

Contact Methods

  • Discord
    メイブ先輩 #8939

Mayube's Achievements

  1. Decided to go a little overboard here for my first post on the LTT forums, so here's a fully functional Login AND Register script in PHP, complete with input validation and exit codes + messages, all in only 88 lines of code! <?php if (isset($_POST['login']) && $_POST['login']) { if (!isset['username'] && !isset['email']) { echo 'No username or email provided!'; exit(1); } if (!isset['passwd']) { echo 'No password provided!'; exit(1); } if (!($con = new mysqli('localhost', 'mysql_user', 'mysql_pass', 'users'))) { echo 'Could not connect to database!'; exit(2); } $qry = $con->prepare('SELECT * FROM accounts WHERE ' . ((isset($_POST['username'])) ? 'user' : 'email') . ' = ?'; if (!$qry->bind_param('s', ((isset($_POST['username'])) ? $_POST['username'] : $_POST['email']))) { echo 'Could not query database!'; exit(2); } if (!$qry->execute()) { echo 'Could not query database!'; exit(2); } $qry->bind_result($account); if (($res = $qry->fetch()) === null) { echo 'User does not exist!'; exit(3); } if (!$res) { echo 'Could not query database!'; exit(2); } if (hash("sha256", $_POST['passwd'] . $account['salt']) != $account['passwd']) { echo 'Incorrect password!'; exit(3); } $qry = $con->prepare('UPDATE accounts SET last_login = NOW() WHERE ' . ((isset($_POST['username'])) ? 'user' : 'email') . ' = ?') if (!$qry->bind_param('s', ((isset($_POST['username'])) ? $_POST['username'] : $_POST['email']))) { echo 'Could not update database!'; exit(2); } if (!$qry->execute()) { echo 'Could not query database!'; exit(2); } if (!$qry->affected_rows()) { echo 'Could not query database!'; exit(2); } session_start(); $_SESSION['uuid'] = $account['uuid']; $_SESSION['name'] = $account['user']; echo 'Logged in successfully!'; exit(0); } else { if (!isset($_POST['username']) || !isset($_POST['email'])) { echo 'No username or email provided!'; exit(1); } if (!isset($_POST['passwd'])) { echo 'No password provided!'; exit(1); } if (!($con = new mysqli('localhost', 'mysql_user', 'mysql_pass', 'users'))) { echo 'Could not connect to database!'; exit(2); } $saltStr = ''; $len = random_int(16, 32); for($i = 0; $i < $len; $i++) $saltStr .= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'[random_int(0, 63)]; $saltStr = hash("sha256", $saltStr); $passwd = hash("sha256", ($_POST['passwd'] . $saltStr)); $qry = $con->prepare("INSERT INTO accounts (user, email, passwd, salt) VALUES (?, ?, ?, ?)"); if (!$qry->bind_param('ssss', $_POST['username'], $_POST['email'], $passwd, $saltStr)) { echo 'Could not query database!'; exit(2); } if (!$qry->execute()) { echo 'Could not query database!'; exit(2); } if (!$qry->affected_rows()) { echo 'Could not query database!'; exit(2); } echo 'Account created successfully!'; exit(0); }
×