Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

I use PDO with prepared statement when connecting to my database, and I do this because it is considered a safe way to do so, but one thing I could not help but to wonder was, can submitted data from a form be harmful if you just declare it like:

$entered_email_adress = $_POST['email']; 

before inserting the data into the database? Should you sanitize the submitted data anyway, or is there no reason doing so?

share|improve this question

2 Answers 2

up vote 6 down vote accepted

Assuming you're putting the input data into a parameter in the query, it's secure against SQL injections. Anything you insert into a parameter is treated as data only, and cannot become part of the query syntax. String concatenation, however, is not safe.

So this is safe:

$pdo->query('select * from users where user_id = ?', $_POST['id']);

This is not:

$pdo->query('select * from users where user_id = ' . $_POST['id']);

Keep in mind that you'll need to do appropriate output escaping if you want to use the data in a web page later, in order to stop markup injection and cross-site scripting (XSS) attacks.

share|improve this answer
    
Thank you for the detailed answer, and for sharing the link. I just want to make sure I understood you correctly; if I insert the data a user has typed into a database through PDO with prepared statement, the data isn't actually escaped "permanently", and you still have to do escaping manually anyway when outputing the data in e.g. a user profile page? –  DannyCruzeira Aug 13 '12 at 13:53
    
The data is stored in a canonical format, i.e. it is byte-for-byte what the user gave you. When the data is outputted, you must escape it for the appropriate format you're outputting into. The link I provided gives some examples for outputting untrusted content into HTML and JavaScript. –  Polynomial Aug 13 '12 at 13:54
    
Ok, thanks again. I will check it out. –  DannyCruzeira Aug 13 '12 at 13:56

In my personal experience and from what I've been lead to understand by people more knowledgeable than myself, no sanitation is necessary when using PDO as far as SQL Injection is concerned. In fact, some sanitation solutions have negative impacts (they change the data in a way you might not want it changed.)

While you don't need to sanitize data going into the database while using PDOs, it is still important to sanitize data coming out. For instance, if someone sets their user name to

<script>send_data_to('Russia')</script>

and you just echo the data unsanitized to the world, that could be a problem.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.