开发者

How to make PDO select queries HTML safe?

I'm new to PDO and just started using it. I already inserted, updated and deleted data using it and it's very simple to use the basics.

In a test environment I inserted some HTML codes to the database. Like:

<a href="google.com">Google</a>
<b>Bold text</b>
<u>Underlined text</u>

etc...

I'm trying this out, because I'm using a simple WYSIWYG editor on my site for the users and I want to be sure the data is safe.

Using the following:

$stmt = $dbh->prepare("SELECT * FROM naruto WHERE id = :id AND name = :name");开发者_运维技巧

/*** bind the paramaters ***/
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 5);


/*** execute the prepared statement ***/
$stmt->execute();

/*** fetch the results ***/
$result = $stmt->fetchAll();

/*** loop of the results ***/
foreach($result as $row)
    {
    echo $row['id'].'<br />';
    echo $row['name'];
    echo $row['image'];
    }

Where name is the different HTML codes, the HTML is just executed. So the text is bold and not in the format text< /b>.

I'm wondering if there is a function for PDO to stop this. Or do I just need to use htmlentities and strip_tags?

Thanks in advance


Using parameterised queries will protect your database from bad data. It won't protect your HTML as that is a completely different layer.

If you want to allow some HTML, then you need to run the data (just before you display it to the user) through something that will white list the HTML you want to allow.

I believe HTML Purifier is one of the tools of choice for PHP users wanting to do this.


Databases don't particularly care whether the data stored in them is HTML markup or not, and neither do database abstraction layers such as PDO... it's just a string as far as they are concerned. It's up to you to handle the data as HTML or plain text.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜