PHP prevent sql injection tips

PHP prevent sql injection tips
PHP prevent sql injection tips

Tips list for prevent sql injection in PHP:

  1. Avoid $_GET, $_POST and $_REQUEST direct use in SQL query
  2. Check variable value and format before use
  3. Avoid use of $_REQUEST
  4. Use PDO process
  5. Limited Privileges to DB user
  6. Set alert email process on SQL execution failure

1) Avoid $_GET, $_POST and $_REQUEST direct use in SQL query

Avoid use of $_GET, $_POST and $_REQUEST array field without sanitize or validate in SQL query.

$sql = 'SELECT * FROM table_name WHERE id='.$_POST['id'];

2) Check variable value and format before use

Always validate before use variable in SQL query.

$idVal = $_GET['id'];
if(!empty($idVal) && ctype_digit($idVal))
{
    $sql = 'SELECT * FROM table_name WHERE id='.$idVal;
    ....
}

3) Avoid use of $_REQUEST

If form method is pre-defined GET/POST then use defined array in process. In case $_REQUEST use. Suppose validation added for $_GET field and in process $_REQUEST used, there is possibility to injection using POST request.

4) Use PDO process

PHP Data Objects (PDO) is a database abstraction layer. PDO allows you to work with many different types of databases securely. This enables you to support multiple types of database with the common code and protects you from SQL Injection by using Prepared Statements.
PDO Prepared statements >>

5) Limited Privileges to DB user

Analyse your project database user privileges requirement. For example DB user require database create, table create etc., privileges or not and set only limited and required privileges.

6) Set alert email process on SQL execution failure

Set alert email process using try catch or set_error_handler when SQL execution fails or break.

Above are the small tips that will helpful in PHP and MySQL development. If you have more tips for prevent SQL injection or suggestion for above tips, please share it from comment section.