What is SQL Injection and how to fix it

by bootsity on Jun 4, 2019 Philosophy 1099 Views

1. Introduction

In this article, we learn about SQL injection security vulnerability in web application. We see an example of SQL Injection, learn in in-depth how it works, and see how we can fix this vulnerability. We use PHP and MySQL for the examples. The SQL injection is the top exploit used by hackers and is one of the top attacks enlisted by the OWASP community.

2. What is SQL Injection

SQL Injection is a attack mostly performed on web applications. In SQL Injection, attacker injects portion of malicious SQL through some input interfaces like web forms. These injected statements goes to the database server behind a web application and may do unwanted actions like providing access to unauthorised person or deleting or reading sensitive information.
The SQL Injection vulnerability may affect any application powered by database supporting SQL like Oracle, MySQL and others.
SQL Injection attacks are one of the widest used, oldest, and very dangerous application vulnerabilities. The OWASP organization (Open Web Application Security Project) lists SQL Injections in their OWASP Top 10 document as the top threat to web application security.

3. Example of SQL Injection

Let’s create a form in HTML:

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h2>SQL injection in web applications</h2>
  5. <form action="/form-handler.php">
  6. Username:<br>
  7. <input type="text" name="username" value="">
  8. <br>
  9. Password:<br>
  10. <input type="password" name="password" value="">
  11. <br><br>
  12. <input type="submit" value="Submit">
  13. </form>
  14. </body>
  15. </html>

When we click on submit, the form above submits to below PHP script:

  1. <?php
  2.  
  3. mysql_connect('localhost', 'root', 'root');
  4. mysql_select_db('bootsity');
  5.  
  6. $username = $_POST["username"];
  7. $password = $_POST["password"];
  8. $query = "SELECT * FROM Users WHERE username = " . $username . " AND password =" . $password;
  9.  
  10. $re = mysql_query($query);
  11.  
  12. if (mysql_num_rows($re) == 0) {
  13. echo 'Not Logged In';
  14. } else {
  15. echo 'Logged In';
  16. }
  17. ?>

4. How SQL Injection works

In the above example, assume that the user fills up the form as below:

  1. Username: ' or '1'='1
  2. Password: ' or '1'='1

Now our $query becomes:

SELECT * FROM Users WHERE username='' or '1'='1' AND password='' or '1'='1';

This query always returns some rows and results in printing Logged In on the browser. So, here the attacker doesn’t know any username or password that are register in the database, but the attacker is still able to log in.

5. Fixing SQL Injection

Now we understand how SQL injection works in PHP. Generally, the best solution is to use prepared statements and parameterized queries. When we use prepared statements and parameterized queries, the SQL statements are parsed separately by the database engine. Let us see these approaches below:

5.1 Using PDO

We can change our form-handler.php to use PDO:

  1. <?php
  2.  
  3. $dsn = "mysql:host=localhost;dbname=bootsity";
  4. $user = "root";
  5. $passwd = "root";
  6.  
  7. $pdo = new PDO($dsn, $user, $passwd);
  8.  
  9. $username = $_POST["username"];
  10. $password = $_POST["password"];
  11.  
  12. $stmt = $pdo->prepare('SELECT * FROM Users WHERE username = :username AND password = :password');
  13.  
  14. $stmt->bindParam(':username', $username);
  15. $stmt->bindParam(':password', $password);
  16.  
  17. $stmt->execute();
  18.  
  19. if (count($stmt) == 0) {
  20. echo 'Not Logged In';
  21. } else {
  22. echo 'Logged In';
  23. }
  24.  
  25. https://article-realm.com/article/Reference-Education/Philosophy/2509-What-is-SQL-Injection-and-how-to-fix-it.html

URL

https://bootsity.com/php/what-is-sql-injection-and-how-to-fix-it
Tutorial article to describe SQL Injection vulnerability in web application with example in PHP and MySQL

Comments

No comments have been left here yet. Be the first who will do it.
Safety

captchaPlease input letters you see on the image.
Click on image to redraw.

Reviews

Guest

Overall Rating:

Statistics

Members
Members: 17030
Publishing
Articles: 79,412
Categories: 202
Online
Active Users: 5659
Members: 3
Guests: 5656
Bots: 32682
Visits last 24h (live): 55356
Visits last 24h (bots): 64067

Latest Comments

이 주제에 대한 흥미롭고 흥미로운 정보는 볼 가치가있는 프로필에서 찾을 수 있습니다. 짱구 도메인 공식 주소  
안녕하세요. GOOGLE을 사용하여 블로그를 찾았습니다. 이것은 아주 잘 쓰여진 기사입니다. 나는 그것을 북마크하고 당신의 유용한 정보를 더 읽기 위해 돌아올 것입니다. 게시물 주셔서 감사합니다. 꼭 돌아 올게요.   나루토벳    
Pemerintah Indonesia, persetan dengan situs web ini, mereka menipu orang. maxslot88 scam  
Para penipu yang memalukan memangsa orang-orang dengan klaim palsu dan kebohongan.  maxslot88 scam    
Pemerintah Indonesia, persetan dengan para penipu itu, tangkap mereka dan persetan dengan mereka karena telah menipu banyak orang. maxslot88 scam  
Halaman ini dikelola oleh para penipu brengsek, hanya berisi kebohongan, janji palsu, dan trik murahan. Hindari orang-orang bodoh ini.  maxslot88 scam  
귀하가 게시 한 정보는 매우 유용합니다. 추천 한 사이트가 좋았습니다. 공유 해주셔서 감사합니다    네임드벳    
High Class Call Girl Delhi was ex-porn star famous. Recognized her from videos instantly. Fucked like professional on camera. Positions were athletic and deep. She knew angles for pleasure....
나는 그들이 매우 도움이 될 것이라고 확신하기 때문에 사람들을 귀하의 사이트로 다시 보내기 위해 귀하의 사이트를 내 소셜 미디어 계정에 추가하고 공유했습니다.  네임드벳    
IPTV trials can be a useful way to test streaming quality, channel variety, and app compatibility before committing to a paid subscription. I’d definitely check the trial terms carefully,...
on Sep 14, 2026 about IPTV PAID AND TRIAL SUBSCRIPTIONS

Translate To: