Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is mysql_real_escape_string is really safe to use? [duplicate]

Tags:

php

mysql

OK, I have one question before I start coding MySQL in my school project. Is mysql_real_escape_string is really safe to use? I've heard that it's still not really safe to use..So are there any tweaks which makes SQL query secure? I've used mysql_real_escape_string before many times, but not I am building a website for my school, so first thing I've to check is security.

like image 646
Sidd P Avatar asked Jun 16 '11 02:06

Sidd P


People also ask

Is mysql_real_escape_string secure?

PHP provides mysql_real_escape_string() to escape special characters in a string before sending a query to MySQL. This function was adopted by many to escape single quotes in strings and by the same occasion prevent SQL injection attacks. However, it can create serious security flaws when it is not used correctly.

Is mysql_real_escape_string enough?

mysql_real_escape_string is usually enough to avoid SQL injection. This does depend on it being bug free though, i.e. there's some small unknown chance it is vulnerable (but this hasn't manifested in the real world yet).

Is mysql_real_escape_string deprecated?

This extension was deprecated in PHP 5.5. 0, and it was removed in PHP 7.0.

What is the use of mysql_real_escape_string?

The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection.


1 Answers

UPDATE: The answer below was to the best of my knowledge correct at the time of writing. The fact is mysql_real_escape_string is not safe and never really was. You should always use prepared statements instead.

As mysql_* has been removed completely as of PHP 7 the situation has become moot. I've left my original answer for historical purposes below.


mysql_real_escape_string is safe to use if used properly (ie, everywhere you're inserting PHP variables into your queries), but as has been pointed out in the comments it's not the only thing you need to worry about. For example, HTML markup could be inserted into your DB and used for Cross Site Scripting attacks.

You might also want to consider prepared statements as an alternative to mysql_real_escape_string, as they will automatically escape input for you so there's no chance of accidentally forgetting to escape a parameter.

like image 159
GordonM Avatar answered Nov 04 '22 00:11

GordonM