Guest User

Untitled

a guest
Feb 9th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. if (isset($_POST['submit'])){
  2. require_once 'config.php';
  3. $errors = [];
  4.  
  5. foreach($_POST as $field => $value){
  6. if(empty($value)){
  7. //failed
  8. $errors[] = "{$field} is required";
  9. }
  10. if(($field === 'email') && !filter_var($value, FILTER_VALIDATE_EMAIL)){//check valid email
  11. //failed
  12. $errors[] = "{$field} is invalid email";
  13. }
  14. if($field !== 'username' && !preg_match('/^[a-z]*$/i', $value)){
  15. //failed
  16. $errors[] = "{$field} has invalid characters";
  17. }
  18. if($field === 'username') {
  19. if (!preg_match('/^[a-zd_]{4,20}$/i', $value)) {
  20. $errors[] = "{$field} has invalid characters";
  21. } else {
  22.  
  23. $escaped_username = mysqli_real_escape_string($connect, $_POST['username']);
  24. $sql = "SELECT * FROM users WHERE username='$escaped_username'";
  25. $result = mysqli_query($connect, $sql);
  26. $num_matching_usernames = mysqli_num_rows($result);
  27. if($num_matching_usernames > 0){
  28. $errors[] = "{$field} Username already taken";
  29. }
  30. }
  31. }
  32. }
  33.  
  34. // no errors, lets save and send email
  35. if (count($errors) == 0) {
  36. $hashed_password = password_hash($_POST["password"], PASSWORD_DEFAULT);
  37. $fields = ['firstname', 'lastname', 'email', 'username'];
  38. $escaped_values = [];
  39. foreach ($fields as $field) {
  40. $escaped_values[$field] = mysqli_real_escape_string($connect, $_POST['$field']);
  41. }
  42. $sql = "INSERT INTO users (firstname, lastname, email, username, password) VALUES ('{$escaped_values["firstname"]}', '{$escaped_values["lastname"]}', '{$escaped_values["email"]}', '{$escaped_values["username"]}', '$hashed_password')";
  43. mysqli_query($connect, $sql);
  44. // send email
  45. $emailRecipient = $_POST["email"];
  46. $subject = 'Welcome';
  47. $message_body = 'You have successfully created an account ' . $_POST["username"] . '! Welcome.';
  48. mail($emailRecipient, $subject, $message_body);
  49. // TODO be wary about using relative urls on a redirect, its easy to redirect to the wrong page
  50. header("Location: ../index.php");
  51. exit;
  52. }
  53. }
  54.  
  55. // display errors at top of page
  56. if (count($errors) > 0) {
  57. echo "Sorry but an error has occurred, please try again";
  58. echo "<ul>";
  59.  
  60. foreach ($errors as $error) {
  61. echo "<li>" . htmlentities($error) . "</li>";
  62. }
  63. echo "</ul>";
  64. }
  65. ?>
  66.  
  67. if($field !== 'username' && !preg_match('/^[a-z]*$/i', $value)){
  68. $errors[] = "{$field} has invalid characters";
  69. <?php
Add Comment
Please, Sign In to add comment