In the scenario below, $user_id is strings entered by a user. I'm wondering if I still need to escape the strings first with
$email = htmlentities($_POST["email"])and$name= htmlentities($_POST["name"])?$query = "INSERT INTO user ('email','name') VALUES (?,?)"; $this->_query = $this->_pdo->prepare($query); $this->_query->bindValue(1, $email); $this->_query->bindValue(2, $name); $this->_query->execute();I saw some people don't escape the input before insert query but they do escape data before echo it out. Why do thay do this?
$query = "SELECT * FROM users WHERE id = ?"; $this->_query = $this->_pdo->prepare($query); $this->_query->bindValue(1, $user_id); $this->_query->execute(); $data = $this->_query->fetchAll(PDO::FETCH_ASSOC); $output = $data[0]["name"]; $output = htmlentities($output); echo output;Is it neccessary to use htmentities() before and after the query?
-
1Do you understand the difference between SQL and HTML, by chance?Your Common Sense– Your Common Sense2016-12-18 17:50:45 +00:00Commented Dec 18, 2016 at 17:50
-
3Possible duplicate of How can I prevent SQL injection in PHP?u_mulder– u_mulder2016-12-18 17:52:39 +00:00Commented Dec 18, 2016 at 17:52
-
Quotes around tables/columns are incorrect. Use backtickschris85– chris852016-12-18 18:03:44 +00:00Commented Dec 18, 2016 at 18:03
2 Answers
You don't need to escape/convert HTML to avoid a SQL injection if you're using prepared queries. As for when you need to use htmlentities or htmlspecialchars, you will need that if you output user-provided data to a web-page. Not doing that makes you vulnerable to XSS (Cross-Site Scripting) injections, ie. malicious javascript that gets executed in the browser on page load. Recommended reading: XSS Prevention Cheat Sheet and PHP Security Cheat Sheet.
Aside SQL and XSS injection prevention, you may also want to do other checks on user input, such as validating e-mail addresses, username characters, etc. before you input them into your DB. Otherwise you're up for some tedious database cleaning down the road. You may want to look into PHP's filter functions, basic regex that removes everything outside white-listed character ranges, etc.
1 Comment
No; a parameterized query is safe from SQL-injection attacks.
& 3. This is using
htmlentities(), which isn't exactly escaping the output. The primary benefit of using this is it protects you from XSS attacks, which is very different from SQL-injection. This sanitizes user input and prevents a user from running a malicious<script>on your webpage.