简体   繁体   中英

Is Regex for Form Validation if I use the following?

I know there is no harm in adding it either way but I'm curious...

If I was to use htmlentities(); with ENT_QUOTES and then mysql_real_escape_string(); the variable before entering it into the Database, then just use html_entity_decode(); along with stripslashes(); to display the information...

Would this still be safe and secure?

You don't need to use htmlentities before storing data in the database. In fact, it makes things easier later if you don't. Only use htmlentities on strings as you echo them in HTML output (whether you fetched the string from a database or from some other source).

You don't need to apply stripslashes to data after you fetch it from the database. The database has not stored the extra escaping characters -- unless you applied double-escaping by mistake.

Here's the right sequence:

  1. Get data from a form

     $input = $_GET["input"]; 
  2. Apply escaping once .

     $quoted_input = "'" . mysql_real_escape_string($input) . "'"; 
  3. Insert it into the database

     $sql = "INSERT INTO MyTable (column1) VALUES ($quoted_input)"; $success = mysql_query($sql); 
  4. Later fetch it from the database

     $sql = "SELECT column1 FROM MyTable"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); $data = $row["column1"]; 
  5. Apply htmlentities once as you output.

     echo htmlentities($data); 

Maybe you can answer the question on your own if you know what these functions are intended to be used for:

If you just want to protect you from SQL injections, use mysql_real_escape_string for data that is used in MySQL queries. You could also use prepared statements or parameterized query builder (see SQL Syntax for Prepared Statements , PDO – Prepared Statements und Stored Procedures , MySQLi::prepare , et al.).

are you asking if you still need regex as form validation next to all those functions?

if that is what you are asking then in my opinion yes, you can never be safe enough. I've just written a validation class with functions that clean up the code and other functions with regex when I need a specific input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM