What is a good way to escape the URL-parameter in the last line of the code to prevent HTML injection through the parametrized href url? I mean in the: editform.php?id=' . $row["CustomerID"] . '">' part.
require_once 'common.php';
$stmt = $db->query("SELECT * FROM customers ORDER BY CustomerID DESC");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results && $stmt->rowCount() > 0)
{
echo '<h2>Results</h2>';
//Here comes some plain HTML for table design.
//Then a FOR loop.
foreach ($results as $row)
{
echo '<tr>';
echo '<td><a href="editform.php?id=' . $row["CustomerID"] . '">' . $row["CustomerID"] . '</a></td>';
I was thinking to write a function in the common.php. Something like:
function escape($html)
{
return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
Will that be conclusive? Or should I use something like: filter_var($url, FILTER_SANITIZE_URL);
I would use urlencode for link and htmlspecialchars for text.
echo '<td><a href="editform.php?id=' . urlencode($row["CustomerID"]) . '">' . htmlspecialchars($row["CustomerID"], ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") . '</a></td>';
For any component of an URL, you need to URL-encode it (using urlencode
). This will avoid issues in the URL itself with spaces, special characters, and &
.
Then you need to escape the full attribute value with htmlspecialchars
. The same applies to any text you include in your HTML.