2

I was trying to sanitize inputs to my PHP login using addslashes and mysql_real_escape_string. Using addslashes works, but mysql_real_escape_string will not.

Here's an example of what allows me to log in correctly:

$user = addslashes($_POST['user']);<br/>
$password = addslashes($_POST['password']);

And this will not:

$user = mysql_real_escape_string($_POST['user']);<br/>
$password = mysql_real_escape_string($_POST['password']);

Also, some of my other fields contain apostrophes. Nothing is returned when using addslashes, since the entry in the DB isn't escaped. I was wondering if using mysql_real_escape_string could fix this, but I don't know how.

moinudin
  • 134,091
  • 45
  • 190
  • 216
user490895
  • 335
  • 2
  • 7
  • 17
  • 2
    `addslashes()` is NOT acceptable for escaping mySQL data. Can you show some actual user data that fails? And the query you're running? – Pekka Jan 06 '11 at 23:48
  • What do your actual SQL statements look like? `addslashes` isn't going to do what you want.. – Brendan Long Jan 06 '11 at 23:49
  • magic_quotes/addslashes are only ever lawful if `mysql_set_charset("ASCII");` or Latin1 was set. It might fail on newer MySQL servers running in `--ansi` mode etc. – mario Jan 07 '11 at 00:21
  • 1
    Notice: `mysql()*`is deprecated as of PHP 5.5.0, it is not recommended for writing new code as it will be removed in the future. Instead, use [mysqli](http://www.php.net/manual/en/book.mysqli.php) or [PDO](http://www.php.net/manual/en/ref.pdo-mysql.php) –  Feb 10 '13 at 10:15

3 Answers3

12

Always use mysql_real_escape_string instead of addslashes. Make sure you are connected to the database before running it otherwise you will error.

Calum
  • 5,308
  • 1
  • 22
  • 27
  • 2
    If you want to make certain HTML is not active when you echo to screen use htmlentities() before displaying text. Both strategies together will increase security. – mbokil Jul 28 '13 at 15:08
1

Sometimes user may type ', this symbol but sql treat as an different way and let it not allow to insert in to tables,we cant restrict the user so that we use MySQL real escape string to avoid this kind of error

Note: if you implement this it should be connect to database else it wont work

akjoshi
  • 15,374
  • 13
  • 103
  • 121
ganesan
  • 11
  • 1
1

mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

And Most important thing is don't trust user input.

So, use htmlspecialchars and strip_tags for better security.

HADI
  • 2,829
  • 1
  • 26
  • 26