Universal Grasp
Universal Grasp

Reputation: 1845

PHP-PDO: Is PDO safe only for Inputing to the Database not Outputting from DB?

Using PDO you'd moslty come across lines like:

$dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");

$dbh->prepare("SELECT * FROM REGISTRY where name = ?");

$dbh->prepare("UPDATE table_name SET col1= ?");

These are famous to being great for Storing data in the Db, Getting Data from the DB, and Updating data in the Db.

When learning PDO, it's strongly emphasized to NOT bother Sanitizing your data, PDO will do the Sanitization.... You can TRUST it 100%....

Now, when it comes to the safety of output DATA from a query such as:

"SELECT * FROM table_name",

A malicious code like: OR 1=1 will NOT affect the Database... However, now that PDO only took care of the DATA when being stored in the DB for DB Protection, on output, if a column contains malicious code like "<script>alert("Hacked")</script>", this seems to alert "Hacked" in the user's browser.

What precautions is there for this?

Do we have to htmlentities or htmlspecialchars the data manually or what is the best way to secure both the Storing and retrieving and displaying of DATA?

Upvotes: 2

Views: 46

Answers (1)

Alma Do
Alma Do

Reputation: 37365

Data storage

Database has no idea what data is stored in it. If it's correct (i.e. all quotes or whatever are escaped properly) - then data is correct and will be stored correctly. But for what purposes - html/javascript/executable code/script code/or/whatever - DB has no idea, so you'll need to take care about that in your application (or another layer which takes output responsibility).

PDO

And so does PDO - it's intention is not in data logic at all. It's just driver, and, thus, it may provide only proper data escaping in terms of storing in database. That's why all specific things can not be caught there (and they shouldn't)

"Best way"

There's no "best way". Different data needs different ways to maintain safe output. For html, it's htmlspecialchars()/htmlentities() - but for other data types it will be other things. And you should know exactly what are you doing (i.e. what are you outputting). Main idea would be - store your data as it is - in database and provide safe output when it's needed (i.e. when output will be done). I.e. split database, data logic and output and provide correct functioning for each of that part.

Upvotes: 2

Related Questions