Categories
MySQL PHP

Prevent SQL Injection attacks in PHP and MySQL

Place this code in your database connect include, just before the database connection is made.

This ensures that SQL injection attempts are handled before the database is opened.

By doing it up front like this, the input is already escaped and we don't have to deal with it in our other scripts as we use input data.

1
2
3
4
5
6
7
8
9
10
11
12
// ~~~~~~~~~~~~~~~~~~~~ SECURE ALL INPUT FROM SQL INJECTION ~~~~~~~~~~~~~~~~~~~~~~~~ //
// --- escape special characters in input data to prevent SQL injection attacks ---- //
 
// Prevent SQL Injection attacks in POST vars
foreach ($_POST as $key => $value) {
  $_POST[$key] = mysql_real_escape_string($value);
}
// Prevent SQL Injection attacks in GET vars
foreach ($_GET as $key => $value) {
  $_GET[$key] = mysql_real_escape_string($value);
}
// ~~~~~~~~~~~~~~~~~~~ /secure all input from sql injection ~~~~~~~~~~~~~~~~~~~~~~~~ //

Leave a Reply