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开发者_Python百科...
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:
Get data from a form
$input = $_GET["input"];
Apply escaping once.
$quoted_input = "'" . mysql_real_escape_string($input) . "'";
Insert it into the database
$sql = "INSERT INTO MyTable (column1) VALUES ($quoted_input)"; $success = mysql_query($sql);
Later fetch it from the database
$sql = "SELECT column1 FROM MyTable"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); $data = $row["column1"];
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:
htmlentities
is to replace the HTML special characters&
,<
,>
, and"
and characters that can be represented by entity character references. This is used to encode data to be safely put out in any HTML context (especially with ENT_QUOTES so that it even can be used in single quoted attribute values). For example:<textarea><?php echo htmlentities('</textarea>'); ?></textarea>
mysql_real_escape_string
is to replace the special characters in a MySQL string while taking the connection character encoding into account (usingmysql_client_encoding
is required). This is used to encode data to be safely used in a MySQL string. For example:$query = 'SELECT "'.mysql_real_escape_string("\n\r\t\v\f\\\"").'"';
html_entity_decode
is the inverse function tohtmlentities
and replaces HTML character references (both numeric and entity character references).stripslashes
removed the escape character\
.
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.
精彩评论