Cookie and SQL injections

Home » Tutorials » PHP » Cookie and SQL injections
In this lesson we’ll consider COOKIE, which is similar with SESSIONS. Also we’ll discuss problem with safety – SQL injections.
COOKIE is similar with SESSIONS. You can store any data of application in cookie. But what is difference between cookie and session? Cookie stores data in user’s browser, which means that anymore can get cookie, change it, or steal. It means to store login and password in coolie is not good idea. Ok. Why do you need cookie? For example, you can use it in basket. Let’s imagine, you put products to basket, but didn’t finish order. Then you return and you needn’t put products to basket. It’s all thanks to cookie.

The second question is SQL injection. This problem has already decided. But for absolute beginners it is important to understand danger of this problem. The reason is you don’t validate data from thr client. For example, if user enter ‘admin’ or 1=1, query will be SELECT * FROM table_name WHERE user = ‘admin’ or 1=1.
Second part of this query is always true. And some “bad guy” get all data from table. In this lesson we considered example, where sql injection drops database

Code lesson (cookie.php)

//пример со счетчиком посещения страниц
$counter = 0;

if (isset($_COOKIE['count'])) {
  $counter = $_COOKIE['count'];

setcookie("count", $counter);

echo $counter;

Code lesson (injection.php)

<!DOCTYPE html>
        <meta charset="utf-8">

        <form class="" method="post">
            <input type="text" name="name" value="">
            <button type="submit" name="button">Отправить</button>


            $name = $_POST['name'];
            $user = "root";
            $password = "root";
            $mydb = new PDO("mysql:host=localhost;dbname=mydb", "root", "root");
            $sql = "select * from users where user_name = $name"; //пример внедрения sql инъекции
            echo $sql;
            $q = $mydb->query($sql);
            while($res = $q->fetch(PDO::FETCH_ASSOC)) {
                echo "<pre>";
                echo "</pre>";
                echo "<br>";



Submit a Comment

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This