How to prevent code injection in PHP – SQL Injection
In this article we will learn ways to prevent code injection in PHP, using strategies to protect your code and database.
What’s up programmer, how are you? Let’s learn more about PHP and SQL Injection!
The first action you should take is not to use PHP’s mysql library and its functions.
The library is not insecure, but it can leave gaps in some situations that favor some code injection
You can then opt for mysqli or PDO (my recommendation)
In the PDO library you can use prepared statements, which is a very good weapon against SQL Injection
Which is basically this one over here:
$sql = 'INSERT INTO mytable(name, password, status) VALUES(?, ?, ?)';
These interrogations will cause the passed data to be processed to just execute text in the SQL query
Protecting you from possible attacks
The values in question will then be replaced with the bindValue method
Check it out:
These two query steps will help reduce vulnerabilities
The query is not executed after its formation, but after these sets of methods
In addition, other necessary best practices are validations on both the front and the back end.
Firstly requiring that the value passed be in the format that will be inserted into the database
For example: a name, this value cannot contain numbers, so do these validations
And also removing special characters that are not needed, as they are the ones that most injections originate from.
Including blank spaces!
Do not accept request types different from the purpose of the query, for example, when inserting data, check if the request is really a POST and not a GET
Do not display SQL errors to the user, this will make him understand how the bank behaves and also discover details that could harm you
All system errors must have a log for further analysis, and then check for any Injection or brute force intrusion attempts.
In this article we learn how to prevent code injection in PHP
The subject is very broad, but most problems are avoided by using prepared statements and mainly by validating all the data that is passed by the user
The other tips are also important, such as not showing SQL errors, this can reveal the modeling of the bank and then the hacker can invade in some other way