Advertisement
karlakmkj

Sanitizing for Back-end Storage - adding contact

Sep 21st, 2021
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.51 KB | None | 0 0
  1. <?php
  2. $contacts = ["Susan" => "5551236666", "Alex" => "7779991717", "Lily" => "8181117777"];  
  3. $message = "";
  4. $validation_error = "* Please enter a 10-digit North American phone number.";
  5. $name = "";
  6. $number = "";
  7.  
  8. // to make sure the data stored in our database follows consistent formatting. Even though we may want to let users input their phone numbers with or without parentheses or dashes, when we store it in the database, we’ll want to change all phone numbers to the same format.
  9.  
  10.  if ($_SERVER["REQUEST_METHOD"] == "POST") {
  11.    $name = $_POST["name"];
  12.    $number  = $_POST["number"];
  13.    
  14.    if (strlen($number) > 30) {
  15.     $message = $validation_error;
  16.    } else {
  17.      $formatted_number = preg_replace("/[^0-9]/", "", $number); // to remove any character that is NOT the numbers 0 to 9. Remove by “replacing” them with an empty string using "" (2nd argument)
  18.      if (strlen($formatted_number) === 10) {
  19.       $contacts[$name] = $formatted_number;
  20.       $message  = "Thanks ${name}, we'll be in touch.";
  21.      } else {
  22.        $message = $validation_error;
  23.      }
  24.    }
  25. };
  26. ?>
  27.  
  28. <html>
  29.     <body>
  30.   <h3>Contact Form:</h3>
  31.         <form method="post" action="">
  32.             Name:
  33.             <br>
  34.         <input type="text" name="name" value="<?= $name;?>">
  35.             <br><br>
  36.         Phone Number:
  37.         <br>
  38.         <input type="text" name="number" value="<?= $number;?>">
  39.         <br><br>
  40.         <input type="submit" value="Submit">
  41.         </form>
  42.         <div id="form-output">
  43.             <p id="response"><?= $message?></p>
  44.     </div>
  45.     </body>
  46. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement