| Tutorial PHP Script Escape Output |
For example, O'Reilly is represented asO\'Reilly when being used in an SQL query to be sent to a MySQL database. The backslash before the single quote exists to preserve the single quote in the context of the SQL query. The single quote is part of the data, not part of the query, and the escaping guarantees this interpretation.
<?php
$html = array( );$html['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8');
echo "<p>Welcome back, {$html['username']}.</p>";
?>
This example demonstrates the use of another naming convention. The $html array is similar to the $clean array, except that its purpose is to hold data that is safe to be used in the context of HTML.
URLs are sometimes embedded in HTML as links:
<a href="http://host/script.php?var=value">Click Here</a>
In this particular example, value exists within nested contexts. It's within the query string of a URL that is embedded in HTML as a link. Because it's alphabetic in this case, it's safe to be used in both contexts. However, when the value of var cannot be guaranteed to be safe in these contexts, it must be escaped twice:
<?php
$html = array( );
$url = array( );
$url['value'] = urlencode($value);
$link = "http://host/script.php?var={$url['value']}";
$html['link'] = htmlentities($link, ENT_QUOTES, 'UTF-8');
?>
<a href="<?php echo $html['link']; ?>">Click Here</a>
This ensures that the link is safe to be used in the context of HTML, and when it is used as a URL (such as when the user clicks the link), the URL encoding ensures that the value of var is preserved.
For most databases, there is a native escaping function specific to the database. For example, the MySQL extension provides mysql_real_escape_string( ):
<?php
$mysql = array( );
$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT *
FROM profile
WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);
?>
An even safer alternative is to use a database abstraction library that handles the escaping for you. The following illustrates this concept with PEAR::DB:
<?php
$sql = 'INSERT
INTO users (last_name)
VALUES (?)';
$db->query($sql, array($clean['last_name']));
?>
Although this is not a complete example, it highlights the use of a placeholder (the question mark) in the SQL query. PEAR::DB properly quotes and escapes the data according to the requirements of your database.
| Users' Comments (0) |
|
No comment posted








