Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User inputs, clean and sanitize before sending to db

Tags:

html

php

mysql

I've searched a lot of the questions here and I found that they either very old or suggesting using prepared statements PDO which I am not using. So I need your help please.

I have a small discussion/chat box where a user submit a message using a <textarea>

What I need is sanitize and filter the user input so it only accepts plain texts (e.g. no tags, no html tags, no scripts no links, etc). Also, it is important to allow line breaks.

Based on my reading I am doing the following in the following order:

  1. trim()
  2. htmlentities($comment, ENT_NOQUOTES)
  3. mysqli_real_escape_string()
  4. nl2br()

Is what I am doing is right? or I am missing something?

Also is there anything I have to do when echoing the data from the db?

really, appreciate your help and kindness

like image 590
SULTAN Avatar asked Aug 09 '15 16:08

SULTAN


People also ask

Why is it important to sanitize input before inserting it in your database?

Failure to sanitize inputs can lead to attackers including SQL code in form inputs so they can do any number of interesting things, ranging from deleting information from a database to injecting information.

What does it mean to sanitize database inputs?

Input sanitization is a cybersecurity measure of checking, cleaning, and filtering data inputs from users, APIs, and web services of any unwanted characters and strings to prevent the injection of harmful codes into the system.

Why do we need to filter and sanitize input that comes from users?

Therefore, to safeguard the database from hackers, it is necessary to sanitize and filter the user entered data before sending it to the database. Let's have an example of SQL injection to make the things clear.


1 Answers

First, keep the text logical and clean:

trim() -- OK
htmlentities($comment, ENT_NOQUOTES)  -- No; do later
mysqli_real_escape_string()  -- Yes; required by API
nl2br()  -- No; see below

The logic behind those recommendations: The data in the database should be just plain data. Not htmlentities, not br-tags. But, you must do the escape_string in order to pass data from PHP to MySQL; the escapes will not be stored.

But... That is only the middle step. Where did the data come from? Older versions of PHP try to "protect" you be adding escapes and other junk that works OK for HTML, but screws up MySQL. Turn off such magic escaping, and get the raw data.

Where does the data go to? Probably HTML? After SELECTing the data back out of the table, then first do htmlentities() and (optionally) nl2br();

Note, if you are expecting to preserve things like <I> (for italic), you are asking for trouble -- big trouble. All a hacker needs to do is <script> ... to inject all sorts of nastiness into your web page and possibly your entire system.

like image 150
Rick James Avatar answered Sep 17 '22 13:09

Rick James