www.webdeveloper.com
Results 1 to 8 of 8

Thread: Php Form validation/ Removing unused post variables

  1. #1
    Join Date
    Jun 2014
    Posts
    3

    Php Form validation/ Removing unused post variables

    I have two questions about my form , how do i prevent the form from sending empty non required fields (like if someone doesn't have a phone number, also how do i prevent the form from sending harmful characters to my server ?
    I did some research and i think the answer may be in ISEMPTY but i don't know how to implement it.

    This is my form validation
    Code:
    $("#myForm").on('valid', function(e){      e.preventDefault();      
          var name = $("input#name").val();
          var email = $("input#email").val();
          var phone = $("input#phone").val();
          var message = $("textarea#message").val();
          var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;
         $.ajax({
            type:"POST",
            url:"bin/mail.php",
            data: dataString,
            success: function(){
              $(".contactform").html("<div id='thanks'></div>");
              $('#thanks').html("<h1 class='text-center form_submit_text'>Thanks</h1>")
               .append("<h2 class='text-center form_submit_text'>Hi " + name + ", we will contact you soon </p>")
               .hide()
               .fadeIn(1500);
            }
         });
        return false;
        });

    This is my mail
    PHP Code:
    <?php$name $_POST["name"];$email $_POST["email"];$phone $_POST["phone"];$message $_POST["message"];$msg "Name:$nameEmail:$emailPhone:$phoneComment:$message";function checkInput($msg) {        $msg = @strip_tags($msg);        $msg = @stripslashes($msg);        $invalid_characters = array("$""%""#""<"">""|");        $msg str_replace($invalid_characters""$msg);        return $msg;    }$to "rebecca.charlotte.adams@gmail.com";$subject "The Brass Teacher Mail";$message $msg;$headers "Contact form enquiry";mail($to,$subject,$message,$headers);?>

  2. #2
    Join Date
    Jun 2014
    Location
    India
    Posts
    7
    strip_tags() is a function used to strip of all the tags form the code. If you want to prevent people from submitting harmful tags/code you can implement it as follows.
    <code>
    <?php
    $text='Hello' ;
    if(strip_tags($text)==$text)
    {
    echo 'safe' ;
    }
    else
    {
    echo 'unsafe' ;
    }

    ?>

  3. #3
    Join Date
    Jun 2014
    Location
    India
    Posts
    7
    Sorry for the reply above I just accidentally posted it and can't find the delete button. However, to prevent any harmful data from being submitted to your database you can implement something like this below.strip_tags() function removes tags form the data.

    Code:
    	if(strip_tags($_POST["name"])==$_POST["name"] AND strip_tags($_POST["email"]==$_POST["email"] and so on check all fields you have similarly)
    	{
    		//Store data to database
    	}
    	else
    	{
    		//Generate some error
    	}
    What the above code does is check if strip_tags[$var]==$var. If it is equal the data is not harmful and can be stored in database. If it is not equal the user has submitted some harmful data and it will be rejected.

    I don't think submitting empty data to database would be a problem because even if you do not submit data it would be empty however you can avoid submitting spaces by using trim() command.

  4. #4
    Join Date
    Jun 2014
    Posts
    3
    So this form doesnt actually send to a database it just uses mail to send an email.

    so would

    <CODE> if(strip_tags($_POST["name"])==$_POST["name"] AND strip_tags($_POST["email"]==$_POST["email"] and so on check all fields you have similarly)
    {
    //Store data to database
    }
    else
    {
    die();
    } </CODE>

  5. #5
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    The shortest form:
    PHP Code:
    $email = (!empty($_POST['email'])) ? $_POST['email'] : ''// or null instead of '' if you prefer 
    You can write it a bit more legibly as:
    PHP Code:
    $email '';
    if(!empty(
    $_POST['email'])) {
        
    $email $_POST['email'];

    For fields where 0 is a valid entry, use isset() instead:
    PHP Code:
    $number = (isset($_POST['number'])) ? $_POST['number'] : ''
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  6. #6
    Join Date
    Jun 2014
    Posts
    3
    So as far i can tell it only sends the email if has content , but if it doesnt it sends blank?

    So how would i make it so no harmfull characters can be sent to my email address? Note this is not going through any database , i just need to strip the headers.

  7. #7
    Join Date
    May 2014
    Posts
    49
    Pre-firstly (yes I just added this in), this should be sanitized. Perhaps with encodeURIComponent. JS is not really my field.

    PHP Code:
    var dataString 'name=' name '&email=' email '&phone=' phone '&message=' message
    Maybe: ?????
    PHP Code:
    var dataString 'name=' encodeURIComponent(name) + '&email=' encodeURIComponent(email) + '&phone=' encodeURIComponent(phone) + '&message=' encodeURIComponent(message); 
    I think there is a better way in jQuery, but... not my field of expertise.


    Firstly, formatting your code to be more readable would be nice:
    PHP Code:
    <?php
    $name 
    $_POST["name"];
    $email $_POST["email"];
    $phone $_POST["phone"];
    $message $_POST["message"];

    $msg "Name:$nameEmail:$emailPhone:$phoneComment:$message";

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

    $to "rebecca.charlotte.adams@gmail.com";
    $subject "The Brass Teacher Mail";
    $message $msg;
    $headers "Contact form enquiry";
    mail($to,$subject,$message,$headers);
    ?>
    Your message seems to be turning $name into $nameEmail and looks unreadable, let's fix that and add some new lines too: \n
    PHP Code:
    $msg "Name: $name\nEmail: $email\nPhone: $phone\nComment:\n$message"
    It seems you already have a function that cleans out characters you don't want checkInput, however you don't use it.

    Let's change that too:

    PHP Code:
    $msg "Name: $name\nEmail: $email\nPhone: $phone\nComment:\n$message";
    $msg checkInput($msg); 
    $headers = "Contact form enquiry"; is not the proper usage of headers, let's just remove it all together.

    I'd also like to trim all the post data to get rid of white space, so right up the top let's do some trimming.

    PHP Code:
    foreach ($_POST as &$var) {
        
    $var trim($var);

    Notice the & before the $var, this means instead of making a copy of the string, it will reference the original copy.

    Actually, let's just write it up in a big commented mess

    PHP Code:
    <?php

    function checkInput($msg) { // We'll just use the one you already had here
        
    $msg = @strip_tags($msg);
        
    $msg = @stripslashes($msg);
        
    $invalid_characters = array("$""%""#""<"">""|");
        
    $msg str_replace($invalid_characters""$msg);
        return 
    $msg;
        }

    foreach (
    $_POST as &$var) { // That & is tricky
        
    $var trim($var); // remove starting and ending whitespace (spaces/newlines/etc) from all submitted data
    }

    $noneMustBeEmpty = ['name','email','phone','message'];
    foreach (
    $noneMustBeEmpty as $toTest) {
        if (empty(
    $toTest)) {
            
    $errors[] = "$toTest must be filled in."
        
    }
    }

    if (
    count($errors)) { // If there is missing data we say what is missing and terminate the script
        
    echo implode("\n"$errors); // this squishes the array data into a string separated by new lines
        
    exit;  // you may want to do something else here, but this is just my quick answer
    }

    $name $_POST["name"];
    $email $_POST["email"];
    $phone $_POST["phone"];
    $message $_POST["message"];

    //$msg = "Name:$nameEmail:$emailPhone:$phoneComment:$message";
    $msg "Name: $name\nEmail: $email\nPhone: $phone\nComment:\n$message";
    $msg checkInput($msg); // Removing everything you didn't want

    $to "rebecca.charlotte.adams@gmail.com";
    $subject "The Brass Teacher Mail";
    $message $msg;

    //$headers = "Contact form enquiry"; // This does nothing good, it's not used like that

    $result mail($to,$subject,$message,$headers); // we should check the result

    if ($result) { // you may want to do something else here, but this is just my quick answer
        
    echo 'Mail added to send queue'// this does not mean the email is or will be received, but it's the closest we can get at this point
    } else {
        echo 
    'Error, mail not sent';
    }
    ?>
    Please note, I didn't test any of this code or think about it too much, it was a spur of the moment quick thing. Those don't always work, but it's a start.

    http://www.php.net/manual/en/function.mail.php

  8. #8
    Join Date
    May 2014
    Posts
    684
    1) It's a REALLY bad idea to override a natural forms behavior with scripttardery; and if you DO, the form should still work scripting off as a normal submit... so where's your actual form.

    2) You should NEVER trust that your scripting will be what sends the form, so any 'validations' you do should ALSO be done server side...

    3) Stop making PHP variables for no reason, they already exist inside $_POST, use them.

    4) in JS if you have multiple VAR declarations in a row, you only need to say VAR once, then comma delimit the rest!

    This all really reeks of putting JS on the page before you had it working without scripting FIRST... and as the unwritten rule of JS goes "If you can't make the page work without scripting FIRST, you likely have no business adding JavaScript to it!"

    Scripting should enhance, not replace functionality -- which is why you really should have markup and server-side doing everything before you even THINK about throwing scripting at it, particularly for a form!

    Could we see the actual form? Where is your PHP side validation equivalent to your scripted one, since you should have done that before even playing around with client side "validation" (which doesn't actually do a blasted thing in terms of security)
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles