Results 1 to 8 of 8

Thread: Php Form validation/ Removing unused post variables

  1. #1
    Join Date
    Jun 2014

    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
    $("#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;
            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>")
        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
    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.
    $text='Hello' ;
    echo 'safe' ;
    echo 'unsafe' ;


  3. #3
    Join Date
    Jun 2014
    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.

    	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
    		//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
    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
    } </CODE>

  5. #5
    Join Date
    Aug 2004
    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 '';
    $_POST['email'])) {
    $email $_POST['email'];

    For fields where 0 is a valid entry, use isset() instead:
    PHP Code:
    $number = (isset($_POST['number'])) ? $_POST['number'] : ''
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  6. #6
    Join Date
    Jun 2014
    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
    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:
    $email $_POST["email"];
    $phone $_POST["phone"];
    $message $_POST["message"];

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

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

    $to "rebecca.charlotte.adams@gmail.com";
    $subject "The Brass Teacher Mail";
    $message $msg;
    $headers "Contact form enquiry";
    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:

    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);

    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 {
    '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.


  8. #8
    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)

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



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.15148 seconds
  • Memory Usage 2,980KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (2)bbcode_code
  • (11)bbcode_php
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (8)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (8)postbit
  • (8)postbit_onlinestatus
  • (8)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates