Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- require_once "conn.php";
- // Error initialization
- $globalError = "";
- $usernameError = "";
- $passwordError = "";
- $usernameMinLength = 5;
- $usernameMaxLength = 60;
- $passwordMinLength = 8;
- $passwordMaxLength = 64;
- // Function used to clear strings from special chars
- function clear_string($str)
- {
- $str = str_replace(' ', '-', $str);
- return preg_replace('/[^A-Za-z0-9\-]/', '', $str);
- }
- if(isset($_POST['name']) && $_POST['name'] != "") // Checking if there is username input
- {
- if(strlen ($_POST['name']) >= $usernameMinLength && strlen ($_POST['name']) <= $usernameMaxLength) // Check username length criteria
- {
- if(isset($_SESSION['username'])) // Dont allow register if user is already logged in
- {
- $globalError = "Already registered, please <b>Logout</b> to register a new <b>User</b>";
- }
- else // If user is NOT logged in , then allow register
- {
- if($_POST['name'] == clear_string($_POST['name'])) // Check if username contains special characters, if username = stripped username, then continue, otherwise give error
- {
- if(strlen ($_POST['password']) >= $passwordMinLength && strlen ($_POST['password']) <= $passwordMaxLength) // Check if password is long enough
- {
- { // Check if username exists
- $sql = "SELECT username FROM users";
- $result = $conn->query($sql);
- if ($result->num_rows > 0)
- {
- $usernameError = "Username is <b>Already</b> taken!";
- }
- }
- $hashPassword = hash('sha256', $_POST['password']); // Hash the input passoword
- $sql = "INSERT INTO users (username, password)
- VALUES ('" . $_POST['name'] . "', '" . $hashPassword . "')"; // Put name and password in query
- if ($conn->query($sql) === TRUE) // Test if query is successful
- {
- header("Location: login.php");
- }
- }
- else
- {
- $passwordError = "Password doesnt fit the <b>requrements</b>, must be " . $passwordMinLength . " to " . $passwordMaxLength . " characters <b>Long</b>";
- }
- }
- else // If username contains special chars
- {
- $usernameError = "Username contains special characters, try with " . clear_string($_POST['name']); // Throw username error
- }
- }
- }
- else
- {
- $usernameError = "Username doesnt fit the <b>requrements</b>, must be " . $usernameMinLength . " to " . $usernameMaxLength . " characters <b>Long</b>";
- }
- }
- $conn->close(); // Closing the SQL connection if no user is logged in
- ?>
Add Comment
Please, Sign In to add comment