Tuesday 8 March 2016

php - Where to use mysql_real_escape_string to prevent SQL Injection?



I'm in trouble with a group of hackers. they hacked my client's site few times, and my client gets more angry :( my client lost his database (which has hundreds records), and had to enter all :(



now I'm following some more introductions;





  • fixed file permissions

  • changed ftp and host login info

  • cleared all remote mysql accesses



now working on SQL Injection issue. I added mysql_real_escape_string to admin panel login paramaters. So where else should I use this mysql_real_escape_string ? I have few email forms at site, I dont think i need to add there...



I have an index.php as a mainpage. Should I do anything for this page to prevent any sql injection attack via url like index.php?somesql= ?




Please advise me! I appreciate so much!!! :(






for example:



I have such code;



public function showDetails($id) {


// SQL Jobs Details
$this->sql_job = "SELECT * FROM jobs WHERE id=".mysql_real_escape_string($id);
$this->rst_job = mysql_query($this->sql_job);
$this->row_all = mysql_fetch_assoc($this->rst_job);

// SQL State
$this->sql_state = "SELECT title FROM state WHERE id=" . $this->row_all[$this->tbl_jobs['f4']];
$this->rst_state = mysql_query($this->sql_state);
$this->row_state = mysql_fetch_assoc($this->rst_state);

........


is it enough to use mysql_real_escape_string for $id . not for $this->row_all[$this->tbl_jobs['f4']]


Answer



Basically, each time you use some unsafe data (user input, value from a database, a file or an external website, i.e. any data that you are not 100% sure that it is safe) in a SQL query, you should escape it using mysql_real_escape_string. Note that according to OWASP, this function is not secure for escaping dynamic table names (but this is far less common than "basic" user input insertion).



I suggest you to have a look at the whole OWASP article on SQL injection, and also to browse the rest of the website. It's a great source of information about security in web applications.



IMO, the preferred way of preventing SQL injection is to use prepared statements.




Please remember that if you do choose to use mysql_real_escape_string() it only works when
used inside a string that is delimited by quotes. Never use it on
any unquoted values. This includes numeric values; instead, validate that the user-input is actually numeric.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...