Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Regular Coder LearningCoder's Avatar
    Join Date
    Jan 2011
    Location
    The Pleiades
    Posts
    912
    Thanks
    76
    Thanked 28 Times in 28 Posts

    Question validating form before submitting to db

    Hello, I am trying to validate my form using php and would like some advice as this is the first time I have attempted this.

    I have a script which runs when the user clicks the submit button. What I am trying to do is validate the user input before inserting it into the database.
    This is the script:
    Code:
    <?php
    session_start();
    
    $dbhandle = mysql_connect('localhost', 'root', '')
         or die("Unable to connect to MySQL");
     
    $selected = mysql_select_db("commentdatabase",$dbhandle)
         or die("Could not select the database");
    
    $name = check_input($_POST['fname']);  
    $loc = check_input($_POST['loc']);  
    $com = check_input($_POST['com']); 
    
    function check_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    } 
    
    $sql = "INSERT INTO userinfo (name, location, comment) VALUES ('{$name}','{$loc}','{$com}')";
    
    if(!mysql_query($sql, $dbhandle)) {
    	 die('Error: ' . mysql_error());
    }
    
    header('Location: ../contact.php');
    
    mysql_close();
    
    ?>
    What's happening is that when it is submitted to the database, it is displaying < and > characters as &lt; and &gt;. Yet once being redirected with the header function the input is displayed with the < and > signs. I'm not sure if the function in the action script is in the wrong place or not. I have tried moving it around above and below the post variables.

    Just looking for a bit of advice really.

    Thank you,

    Regards,

    LC.

  • #2
    New Coder
    Join Date
    Jun 2011
    Location
    Australia
    Posts
    13
    Thanks
    3
    Thanked 1 Time in 1 Post
    I'm ubernoob also, but from what I understand of your post... the data going into the database has been htmlspecialchars()'d. Which means that < and > will now be the &lt; and &gt; codes. I'm assuming that after the user has submitted the comment you are showing them the result on a webpage, correct? If so, htmlspecialchars() on your data will be displayed as the actual html tags in the browser.

    Sorry if I have misunderstood

  • #3
    Regular Coder LearningCoder's Avatar
    Join Date
    Jan 2011
    Location
    The Pleiades
    Posts
    912
    Thanks
    76
    Thanked 28 Times in 28 Posts
    I believe that is correct. I have used htmlspecialchars($data, ENT_QUOTES);

    This takes each input, strips any html characters and also any double or single quotes.

    I'm not sure on how to stop characters such as : %&@][~?#*^! can be stopped from being entered into the database.

    I have some javascript which achieves this but i cannot work out how to do the same in php language.

    Can any one assist me in how to stop the user entering the above characters using php?

    This is my current code:
    Code:
    <?php
    session_start();
    
    $dbhandle = mysql_connect('localhost', 'root', '')
         or die("Unable to connect to MySQL");
     
    $selected = mysql_select_db("commentdatabase",$dbhandle)
         or die("Could not select the database");
    
    $name = check_input($_POST['fname']);  
    $loc = check_input($_POST['loc']);  
    $com = check_input($_POST['com']); 
    
    function check_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES);
        return $data;
    } 
    
    $sql = "INSERT INTO userinfo (name, location, comment) VALUES ('{$name}','{$loc}','{$com}')";
    
    if(!mysql_query($sql, $dbhandle)) {
    	 die('Error: ' . mysql_error());
    }
    
    header('Location: ../contact.php');
    
    mysql_close();
    
    ?>
    Regards,

    LC.
    Last edited by LearningCoder; 04-19-2012 at 12:00 AM.

  • #4
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    Quote Originally Posted by LearningCoder View Post
    I believe that is correct. I have used htmlspecialchars($data, ENT_QUOTES);
    Probably I am not answering your question, but here are 2 messages quoted directly from php.net:

    Note:

    If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.
    They're talking about: mysql_real_escape_string()

    Note:

    mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.




    I don't know, I don't care, and it doesn't make any difference!
    -Albert Einstein-




  • #5
    Regular Coder LearningCoder's Avatar
    Join Date
    Jan 2011
    Location
    The Pleiades
    Posts
    912
    Thanks
    76
    Thanked 28 Times in 28 Posts
    Ok, thank you for that information. I will also use the mysql_real_escape_string() within the function.

    I'm currently trying to use the strstr method but no sites whatsoever explain it simply enough for me.

    Regards,

    LC.

  • #6
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    Quote Originally Posted by LearningCoder View Post
    Ok, thank you for that information. I will also use the mysql_real_escape_string() within the function.

    I'm currently trying to use the strstr method but no sites whatsoever explain it simply enough for me.

    Regards,

    LC.
    Within a string such as "billy@gmail.com", strstr() finds the 1st occurrence/position of a substring (for example the '@' sign is a substring), and returns that substring plus the string that follows after it. There is also an option for returning only the characters that come before the substring we supply.


    Example:
    PHP Code:
    $email  'billy@gmail.com';

    $g strstr($email'@');
    echo 
    $g//prints @gmail.com

    $b strstr($email'@'true); //As of PHP 5.3.0 you can add a third parameter to true or false. When true, strstr() will return the string that comes before the substring we specified (in this case the '@' sign)
    echo $b//prints billy 
    For example in Javascript you would do something like this:
    Code:
    var email = "billy@gmail.com"; 
    
    var g = email.slice( email.indexOf('@') ); 
    console.log(g); //prints @gmail.com
    
    var b = email.slice(0, email.indexOf('@')); 
    console.log(b); //prints billy




    I don't know, I don't care, and it doesn't make any difference!
    -Albert Einstein-




  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    Validate the fields as you rread them in to make sure that the field contains something reasonable for what the field is supposed to contain.

    Unless the field can validly contain something that could be confused with the SQL query (when writing the field to the database) or with HTML tags (when writing to a web page) there is no need to escape the data since escaping is only required to avoid such confusion.

    htmlentities and similar should only be used before outputting to HTML since if you use it earlier and then use the data somewhere other than HTML you will have invalidated it yourself.

    You can avoid needing to escape data to be inserted into a mysql database completelt if you use either mysqli or PDO and then use PREPARE and BIND statements instead of QUERY - as that keeps the query in the prepare statement and the data in the bind statement so they can't possibly be confused.

    The most important part of validation is to make sure the fields contain something that looks reasonable - no point in filling a database with junk. Use is_numeric and similar where there are functions like that which can validate what the field is allowed to contain. If specific functions aren't available then visit http://au.php.net/manual/en/book.filter.php and see if suitable filters are available to use (eg. for email addresses). If neither of those options can be used then set up regular expressions to validate the input.

    Validation is an input function. Escaping is an output function.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

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