How to prevent SQL injection in PHP?

SQL injection usually occurs when you ask a user for input, like their username/userid, and instead of a name/id, the user gives you an SQL statement that you will unknowingly run on your database. Like in the following example.

$unsafe_variable = $_POST['user_input'];

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");

                                                                                                                                               

User can input something like " value'); DROP TABLE table;--, and the query becomes:

 

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

 

To make your application SQL injection proof always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

Basically we have two options to achieve this:

Using PDO (for any supported database driver):

1.    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

2.    $stmt->execute(array('name' => $name));

3.    foreach ($stmt as $row) {

4.       // do something with $row}

 

Using MySQLi (for MySQL):

1.    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');

2.    $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

3.  $stmt->execute();

4.  $result = $stmt->get_result();

5.  while ($row = $result->fetch_assoc()) {

6.     // do something with $row}

 

If system connect to a database other than MySQL, there is a driver-specific second option refer (e.g. pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

 

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this. To disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 

In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are thrown as PDOException.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although user can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) user tell the database engine where user want to filter on. Then call execute, the prepared statement is combined with the parameter values.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters user send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

Another benefit of using prepared statements is that if we execute the same statement many times in the same session it will only be parsed and compiled once, giving some speed gains.

Oh, and since user asked about how to do it for an insert, here's an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array('column' => $unsafeValue));



Was this article helpful?



You are freelancing Ninja?

Try Toogit Instant Connect today, The new virtual assistant for your freelancing world.


How to hire a php developer today?

Now days, Freelancing is simplest, easiest and best way to Hire PHP developers for full-time or part-time.

Once you've decided to hire dedicated PHP developer instantly, you need to follow some basic steps to Hire PHP developer for website design & development. The first place to start with is your outsourced project itself, define outline of your website concept with complete requirement and summarizing the vital elements and analyze your requirement for determine the employment type (individual/agency), budget and share your requirement on freelance platform. Within 24 hours you get top PHP developers proposals, you need to scan their portfolio and shortlisted them, preferred only experienced PHP developer because hiring experience person is always better deals. And finally invite them for interview to assess their abilities. If you aren't from a technical background, seek someone proficient to conduct a technical interview of PHP developers.

What are the benefits to hire a php developer near me?

Hire PHP developer to build a website as per the requirement of your business in a convenient manner.

A team of professionals can undertake the requirement of your business and can turn your ideas into reality.

Hiring PHP experts is a must for you if you want to build a best PHP based site with a professional look. Top Web developers from all over the world are opting for this software to build a site because of its cost effectiveness, flexibility, simplicity and free availability. Top PHP developers for hire to accomplish your business projects.


  • Flexible option: Our multiple models are designed to give you the flexibility in hiring your team at your own budget and project requirements.
  • Build your own team: Choose from a variety of technologies and create your dream team or your own IT team.
  • Transparency at all levels: Options to choose from a pool of talented resources, interviewing them as per your own standards and hiring the right resource.
  • Complete control: Assign tasks at your own will or give the control to the team to lead the development.

How to create a website using PHP for new company?

If you decide to create a website in PHP and you don't know PHP programming and website design. Freelance market is best choice for development of an attractive and fully functional website. You just focus on your business and define the primary purpose of your website, your specific user experience and fundamental goal of your website. Following points are step by step guide for creating a website for business.


  • Define primary goal and complete requirement of your website.
  • Define domain name, it is one of the most important features of your PHP website (i.e. URL).
  • Choose a great experienced PHP website developer for web page design.
  • Choose your favourite website template.
  • Test and publish your website.

What are php developers?

PHP (Hypertext Pre-processor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

PHP Programming Languages most commonly used for web site and web Application Development. PHP could be use for a general purpose, server-side scripting language run a web server that is designed to form dynamic pages and applications.

PHP as a web development option is secure, quick and a reliable that gives lots more advantages to form it accessible to a lot of people. It is to be given a thought on what has made PHP Programming as one of the most commonly programming language for the online business.

Mistakes while hiring the Top PHP Developers

Common mistake that need to be avoided while hiring a PHP developer

  1. Not examining the previous work effectively:Basically, you have to judge the work of the PHP Developer when you are trying to hire them. Of course, you'll have some idea of the skills that are required for the task and some assumptions on how you would like to proceed additional.
  2. Looking within the region: 'I would prefer to hire a PHP Developer who belongs to my region' this can be the fact that the majority of the businesses think and work in this direction. Well, most of them think that this the simplest way; communication becomes straightforward, problems may be solved with ease and at a faster rate.
  3. Ignoring support and communication: Make sure that your communication is perfect. A proper mode of communication should be selected by the company for solving and reviewing the latest updates and problems. So, while interviewing, test their analytical, decision-making, and problem-solving ability, and also check whether the developer is able to understand and implement the requirements in the project easily or not.
  4. Pricing issue: Do you agree on variable pricing? You never know how much money are going to be spent throughout the process and how many months it would take for the website to go live. This problem arises when working with an offshore. So, in the first interview itself, talk about all the issues clearly. Make sure you provide the detailed contract which is duly signed by the offshore company.