PHP Security: Escape Output
Escaping output intended for a database will not suffice when sending that same output to a Web browser—data must be escaped according to its destination. you should always be aware of the
destination of your output and any special characters or commands that destination
may accept and act upon—and be ready escape those characters or commands
accordingly.
Escape HTML Output
To escape output intended for a Web browser, PHP provides htmlspecialchars();
and htmlentities();, the latter being the most exhaustive and, therefore, recommended
function for escaping.
echo htmlentities($user_message, ENT_QUOTES, ’UTF-8’);
Is much more safter than raw $user_message output.
Escape SQL Output
You should escape output destined for a database such as a sql statement with the *_escape_string() function. You should also use prepared statements when possible, prepared statements are available for all database engines in PHP5 using the PDO Driver (PHP Data Objects), if database does not support prepared statements PDO emulates this feature.
The use of prepared statements allows you to have placeholders in an SQL statement.This statement can then be used multiple times throughout an application, substituting new values for the placeholders.
// First, filter the input $clean = array(); if (ctype_alpha($_POST[’username’])) { $clean[’username’] = $_POST[’username’]; } // Set a named placeholder in the SQL statement for username $sql = ’SELECT * FROM users WHERE username = :username’; // Assume the database handler exists; prepare the statement $stmt = $dbh->prepare($sql); // Bind a value to the parameter $stmt->bindParam(’:username’, $clean[’username’]); // Execute and fetch results $stmt->execute(); $results = $stmt->fetchAll();
Escape SQL Output - What are prepared statements?
Their is a descriptive article on mysql.com.
You can have a simple query with a defined variable and use it many times with different WHERE or Input perimeters.
Facts:
- More Secure (separates sql logic from user data)
- No need for special function to escape backslash or double quotes.
- Use of prepared statements introduces pre-parsing, if query run many times it leads to speed increase.
- Lower CPU with less binary translation
- limited to DML (INSERT, REPLACE, UPDATE, and DELETE), CREATE TABLE, and SELECT queries
- If only one query is needed, dont use prepared statements as it will be slower.











