Guest User

Untitled

a guest
Feb 7th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. <?php
  2.  
  3. require_once "conn.php";
  4.  
  5. // Error initialization
  6. $globalError = "";
  7. $usernameError = "";
  8. $passwordError = "";
  9.  
  10. $usernameMinLength = 5;
  11. $usernameMaxLength = 60;
  12. $passwordMinLength = 8;
  13. $passwordMaxLength = 64;
  14.  
  15. // Function used to clear strings from special chars
  16. function clear_string($str)
  17. {
  18. $str = str_replace(' ', '-', $str);
  19. return preg_replace('/[^A-Za-z0-9\-]/', '', $str);
  20. }
  21.  
  22. if(isset($_POST['name']) && $_POST['name'] != "") // Checking if there is username input
  23. {
  24. if(strlen ($_POST['name']) >= $usernameMinLength && strlen ($_POST['name']) <= $usernameMaxLength) // Check username length criteria
  25. {
  26. if(isset($_SESSION['username'])) // Dont allow register if user is already logged in
  27. {
  28. $globalError = "Already registered, please <b>Logout</b> to register a new <b>User</b>";
  29. }
  30. else // If user is NOT logged in , then allow register
  31. {
  32. if($_POST['name'] == clear_string($_POST['name'])) // Check if username contains special characters, if username = stripped username, then continue, otherwise give error
  33. {
  34. if(strlen ($_POST['password']) >= $passwordMinLength && strlen ($_POST['password']) <= $passwordMaxLength) // Check if password is long enough
  35. {
  36. { // Check if username exists
  37. $sql = "SELECT username FROM users";
  38. $result = $conn->query($sql);
  39. if ($result->num_rows > 0)
  40. {
  41. $usernameError = "Username is <b>Already</b> taken!";
  42. }
  43. }
  44. $hashPassword = hash('sha256', $_POST['password']); // Hash the input passoword
  45.  
  46. $sql = "INSERT INTO users (username, password)
  47. VALUES ('" . $_POST['name'] . "', '" . $hashPassword . "')"; // Put name and password in query
  48.  
  49. if ($conn->query($sql) === TRUE) // Test if query is successful
  50. {
  51. header("Location: login.php");
  52. }
  53. }
  54. else
  55. {
  56. $passwordError = "Password doesnt fit the <b>requrements</b>, must be " . $passwordMinLength . " to " . $passwordMaxLength . " characters <b>Long</b>";
  57. }
  58. }
  59. else // If username contains special chars
  60. {
  61. $usernameError = "Username contains special characters, try with " . clear_string($_POST['name']); // Throw username error
  62. }
  63. }
  64. }
  65. else
  66. {
  67. $usernameError = "Username doesnt fit the <b>requrements</b>, must be " . $usernameMinLength . " to " . $usernameMaxLength . " characters <b>Long</b>";
  68. }
  69. }
  70.  
  71. $conn->close(); // Closing the SQL connection if no user is logged in
  72. ?>
Add Comment
Please, Sign In to add comment