-2

I have tried both real escape string and other php methods but I am not sure I am using them correctly. This code shows my input and then the ajax post, where and how would I preform the sanitation?

Please note there is no data base connection so all the character stripping would have to be done in jQuery somehow.

Would this be more of the correct direction to go in?

<?php
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];


$msg = "
Name:$name
Email:$email
Phone:$phone
Comment:
$message";


function checkInput($msg) {
    $msg = @strip_tags($msg);
    $msg = @stripslashes($msg);
    $invalid_characters = array("$", "%", "#", "<", ">", "|");
    $msg = str_replace($invalid_characters, "", $msg);
    return $msg;
}


$to = "email address";
$subject = "name";
$message = $msg;
$headers = "Contact form enquiry";
mail($to,$subject,$message,$headers);
?>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2513718
  • 39
  • 1
  • 8

2 Answers2

0

You perform sanitation immediately before you put the text into some code or specific data format.

So in the code you have here:

  var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;

You would escape each variable before you put it into the URL. You can do that with encodeURIComponent. However, you are using jQuery ajax so you shouldn't be doing that by hand in the first place.

data: { 'name': name, 'email': email, 'phone': phone, 'message': message},

And in the HTML you are generating:

   .append("<h2 class='text-center form_submit_text'>Hi " + name + ", we will contact you soon </p>")

should be:

   var heading = jQuery("<h2>").addClass('text-center').addClass('form_submit_text').text("Hi " + name + ", we will contact you soon);
   $('#thanks').empty().append(heading);

You might also need to do some escaping in your PHP, such as before putting data into SQL.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You validate and sanitize in bin/mail.php. See filter_var for the built in ways to validate and sanitize incoming data. For example, for email you can do

if (filter_var($_POST['email']), FILTER_VALIDATE_EMAIL)) {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
}

Phone numbers would required a regular expression to validate and sanitize (so it only contains numbers and/or re-formats to your preferred format). Free text like $message should use FILTER_SANITIZE_STRING.

Oscar M.
  • 1,076
  • 7
  • 9