{"id":18020702,"url":"https://github.com/inforkgodara/sql-injection","last_synced_at":"2025-07-21T16:32:02.481Z","repository":{"id":110250377,"uuid":"296948779","full_name":"inforkgodara/sql-injection","owner":"inforkgodara","description":"It is a SQL injection vulnerable project with demonstration. It is developed using PHP and MySQL technologies. It also contains a youtube link where fully demonstrated SQL Injection.","archived":false,"fork":false,"pushed_at":"2021-05-24T00:04:16.000Z","size":225,"stargazers_count":18,"open_issues_count":0,"forks_count":17,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-08T10:11:42.202Z","etag":null,"topics":["attack","bypass-login","bypass-login-php-website","login-form-hacking","mysql-database","php","php-login-form","php-small-project","php-sql-injection","php-web-injection","sql-database","sql-injection","sql-injection-attacks","sql-injection-exploitation"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/inforkgodara.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-09-19T20:44:48.000Z","updated_at":"2024-09-30T18:03:15.000Z","dependencies_parsed_at":"2023-11-19T09:15:09.319Z","dependency_job_id":null,"html_url":"https://github.com/inforkgodara/sql-injection","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/inforkgodara/sql-injection","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inforkgodara%2Fsql-injection","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inforkgodara%2Fsql-injection/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inforkgodara%2Fsql-injection/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inforkgodara%2Fsql-injection/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/inforkgodara","download_url":"https://codeload.github.com/inforkgodara/sql-injection/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inforkgodara%2Fsql-injection/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266334065,"owners_count":23912882,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-21T11:47:31.412Z","response_time":64,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["attack","bypass-login","bypass-login-php-website","login-form-hacking","mysql-database","php","php-login-form","php-small-project","php-sql-injection","php-web-injection","sql-database","sql-injection","sql-injection-attacks","sql-injection-exploitation"],"created_at":"2024-10-30T06:07:22.486Z","updated_at":"2025-07-21T16:32:02.472Z","avatar_url":"https://github.com/inforkgodara.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SQL Injection\n\nSQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker). SQL injection must exploit a security vulnerability in an application's software, for example, when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database. (wikipedia). It is used in database database technologies. There have been create basic. We will be using php web application to demonstrate sql injection. \n\n## Demo\n* Video clip on demonstration: https://youtu.be/KH_4s2WVDK0\n\n## Prerequisites\n\nYou must have following programs/packages in order to run this project.\n\n* Apache: 2.4.46\n* PHP: 7.2.33 \n* MariaDB: 10.4.14\n* phpMyAdmin: 5.0.2\n\nNote: the XAMPP server include all above mentioned technologies. https://www.apachefriends.org/download.html \n\n## Simple Login Development Approach\n\nA simple php and MySQL based web application is developed which has registration, login, dashboard and logout. The authentication is very common in modern web application. It is a security mechanism that is used to restrict unauthorized access to member-only areas and tools on a site.\n\nIn this section we'll build a registration system that allows users to create a new account by filling out a web form. But, first we need to create a table that will hold all the user data.\n\n### Step 1: Creating the database table\n\n```\nCREATE TABLE users (\n    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n    username VARCHAR(50) NOT NULL UNIQUE,\n    password VARCHAR(255) NOT NULL,\n    created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n```\n### Step 2: Creating the config script\n\nAfter creating the table, we need create a PHP script in order to connect to the MySQL database server. Let's create a file named \"config.php\" and put the following code inside it.\n\n```\n\u003c?php\n/* Database credentials. Assuming you are running MySQL\nserver with default setting (user 'root' with no password) */\n\ndefine('DB_SERVER', 'localhost');\ndefine('DB_USERNAME', 'root');\ndefine('DB_PASSWORD', '');\ndefine('DB_NAME', 'sql_injection');\n \n/* Attempt to connect to MySQL database */\n$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);\n \n// Check connection\nif($link === false){\n    die(\"ERROR: Could not connect. \" . mysqli_connect_error());\n}\n?\u003e\n```\nNote: Replace the credentials according to your MySQL server setting before testing this code, for example, replace the database name 'sql_injection' with your own database name, replace username 'root' with your own database username, specify database password if there's any.\n\n### Step 3: Creating the registration module\n\nLet's create another PHP file \"register.php\" and put the following example code in it. This example code will create a web form that allows user to register themselves.\n\nThis script will also generate errors if a user tries to submit the form without entering any value, or if username entered by the user is already taken by another user.\n\n```\n\u003c?php\n/* Include config file */\nrequire_once \"config.php\";\n\n/* Define variables and initialize with empty values */\n$username = $password = $confirm_password = \"\";\n$username_err = $password_err = $confirm_password_err = \"\";\n\n/* Processing form data when form is submitted */\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\")\n{\n\n    /* Validate username */\n    if (empty(trim($_POST[\"username\"])))\n    {\n        $username_err = \"Please enter a username.\";\n    }\n    else\n    {\n        /* Prepare a select statement */\n        $sql = \"SELECT id FROM users WHERE username = ?\";\n\n        if ($stmt = mysqli_prepare($link, $sql))\n        {\n            /* Bind variables to the prepared statement as parameters */\n            mysqli_stmt_bind_param($stmt, \"s\", $param_username);\n\n            /* Set parameters */\n            $param_username = trim($_POST[\"username\"]);\n\n            /* Attempt to execute the prepared statement */\n            if (mysqli_stmt_execute($stmt))\n            {\n                /* store result */\n                mysqli_stmt_store_result($stmt);\n\n                if (mysqli_stmt_num_rows($stmt) == 1)\n                {\n                    $username_err = \"This username is already taken.\";\n                }\n                else\n                {\n                    $username = trim($_POST[\"username\"]);\n                }\n            }\n            else\n            {\n                echo \"Oops! Something went wrong. Please try again later.\";\n            }\n\n            /* Close statement */\n            mysqli_stmt_close($stmt);\n        }\n    }\n\n    /* Validate password */\n    if (empty(trim($_POST[\"password\"])))\n    {\n        $password_err = \"Please enter a password.\";\n    }\n    elseif (strlen(trim($_POST[\"password\"])) \u003c 6)\n    {\n        $password_err = \"Password must have atleast 6 characters.\";\n    }\n    else\n    {\n        $password = trim($_POST[\"password\"]);\n    }\n\n    /* Validate confirm password */\n    if (empty(trim($_POST[\"confirm_password\"])))\n    {\n        $confirm_password_err = \"Please confirm password.\";\n    }\n    else\n    {\n        $confirm_password = trim($_POST[\"confirm_password\"]);\n        if (empty($password_err) \u0026\u0026 ($password != $confirm_password))\n        {\n            $confirm_password_err = \"Password did not match.\";\n        }\n    }\n\n    /* Check input errors before inserting in database */\n    if (empty($username_err) \u0026\u0026 empty($password_err) \u0026\u0026 empty($confirm_password_err))\n    {\n\n        /* Prepare an insert statement */\n        $sql = \"INSERT INTO users (username, password) VALUES (?, ?)\";\n\n        if ($stmt = mysqli_prepare($link, $sql))\n        {\n            /* Bind variables to the prepared statement as parameters */\n            mysqli_stmt_bind_param($stmt, \"ss\", $param_username, $param_password);\n\n            /* Set parameters */\n            $param_username = $username;\n            $param_password = md5($password);\n            /* Creates a password hash\n            Attempt to execute the prepared statement */\n            if (mysqli_stmt_execute($stmt))\n            {\n                /* Redirect to login page */\n                header(\"location: login.php\");\n            }\n            else\n            {\n                echo \"Something went wrong. Please try again later.\";\n            }\n\n            /* Close statement */\n            mysqli_stmt_close($stmt);\n        }\n    }\n\n    /* Close connection */\n    mysqli_close($link);\n}\n?\u003e\n \n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003eSign Up\u003c/title\u003e\n    \u003clink rel=\"stylesheet\" href=\"assets/bootstrap.css\"\u003e\n    \u003cstyle type=\"text/css\"\u003e\n        body{ font: 14px sans-serif; }\n        .wrapper{ width: 350px; padding: 20px; }\n    \u003c/style\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cdiv class=\"wrapper\"\u003e\n        \u003ch2\u003eSign Up\u003c/h2\u003e\n        \u003cp\u003ePlease fill this form to create an account.\u003c/p\u003e\n        \u003cform action=\"\u003c?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]); ?\u003e\" method=\"post\"\u003e\n            \u003cdiv class=\"form-group \u003c?php echo (!empty($username_err)) ? 'has-error' : ''; ?\u003e\"\u003e\n                \u003clabel\u003eUsername\u003c/label\u003e\n                \u003cinput type=\"text\" name=\"username\" autocomplete=\"off\" class=\"form-control\" value=\"\u003c?php echo $username; ?\u003e\"\u003e\n                \u003cspan class=\"help-block\"\u003e\u003c?php echo $username_err; ?\u003e\u003c/span\u003e\n            \u003c/div\u003e    \n            \u003cdiv class=\"form-group \u003c?php echo (!empty($password_err)) ? 'has-error' : ''; ?\u003e\"\u003e\n                \u003clabel\u003ePassword\u003c/label\u003e\n                \u003cinput type=\"password\" name=\"password\" autocomplete=\"off\" class=\"form-control\" value=\"\u003c?php echo $password; ?\u003e\"\u003e\n                \u003cspan class=\"help-block\"\u003e\u003c?php echo $password_err; ?\u003e\u003c/span\u003e\n            \u003c/div\u003e\n            \u003cdiv class=\"form-group \u003c?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?\u003e\"\u003e\n                \u003clabel\u003eConfirm Password\u003c/label\u003e\n                \u003cinput type=\"password\" name=\"confirm_password\" autocomplete=\"off\" class=\"form-control\" value=\"\u003c?php echo $confirm_password; ?\u003e\"\u003e\n                \u003cspan class=\"help-block\"\u003e\u003c?php echo $confirm_password_err; ?\u003e\u003c/span\u003e\n            \u003c/div\u003e\n            \u003cdiv class=\"form-group\"\u003e\n                \u003cinput type=\"submit\" class=\"btn btn-primary\" value=\"Submit\"\u003e\n                \u003cinput type=\"reset\" class=\"btn btn-default\" value=\"Reset\"\u003e\n            \u003c/div\u003e\n            \u003cp\u003eAlready have an account? \u003ca href=\"login.php\"\u003eLogin here\u003c/a\u003e.\u003c/p\u003e\n        \u003c/form\u003e\n    \u003c/div\u003e    \n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n### Step 4: Creating the login module\n\nIn this section we'll create a login form where user can enter their username and password. When user submit the form these inputs will be verified against the credentials stored in the database, if the username and password match, the user is authorized and granted access to the site, otherwise the login attempt will be rejected.\n\nLet's create a file named \"login.php\" and place the following code inside it.\n\n```\n\u003c?php\n/* Initialize the session */\nsession_start();\n\n/* Check if the user is already logged in, if yes then redirect him to welcome page */\nif (isset($_SESSION[\"loggedin\"]) \u0026\u0026 $_SESSION[\"loggedin\"] === true)\n{\n    header(\"location: welcome.php\");\n    exit;\n}\n\n/* Include config file */\nrequire_once \"config.php\";\n\n/* Define variables and initialize with empty values */\n$username = $password = \"\";\n$username_err = $password_err = \"\";\n\n/* Processing form data when form is submitted */\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\")\n{\n\n    /* Check if username is empty */\n    if (empty(trim($_POST[\"username\"])))\n    {\n        $username_err = \"Please enter username.\";\n    }\n    else\n    {\n        $username = trim($_POST[\"username\"]);\n    }\n\n    /* Check if password is empty */\n    if (empty(trim($_POST[\"password\"])))\n    {\n        $password_err = \"Please enter your password.\";\n    }\n    else\n    {\n        $password = trim($_POST[\"password\"]);\n    }\n\n    /* Validate credentials */\n    if (empty($username_err) \u0026\u0026 empty($password_err))\n    {\n        /* Prepare a sql query statement */\n        $sql = \"SELECT id, username FROM users WHERE username = '$username' and password = md5('$password')\";\n\n        $result = mysqli_query($link, $sql);\n\n        if (mysqli_num_rows($result) \u003e 0)\n        {\n            session_start();\n\n            /* Store data in session variables */\n            $_SESSION[\"loggedin\"] = true;\n            $_SESSION[\"id\"] = $id;\n            $_SESSION[\"username\"] = $username;\n\n            /* Redirect user to welcome page */\n            header(\"location: welcome.php\");\n        }\n        else\n        {\n            /* Display an error message if there is no row selected. */\n            $password_err = \"The password you entered was not valid.\";\n        }\n        /* Close statement */\n        mysqli_close($link);\n    }\n}\n?\u003e\n \n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003eLogin\u003c/title\u003e\n    \u003clink rel=\"stylesheet\" href=\"assets/bootstrap.css\"\u003e\n    \u003cstyle type=\"text/css\"\u003e\n        body{ font: 14px sans-serif; }\n        .wrapper{ width: 350px; padding: 20px; }\n    \u003c/style\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cdiv class=\"wrapper\"\u003e\n        \u003ch2\u003eLogin\u003c/h2\u003e\n        \u003cp\u003ePlease fill in your credentials to login.\u003c/p\u003e\n        \u003cform action=\"\u003c?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]); ?\u003e\" method=\"post\"\u003e\n            \u003cdiv class=\"form-group \u003c?php echo (!empty($username_err)) ? 'has-error' : ''; ?\u003e\"\u003e\n                \u003clabel\u003eUsername\u003c/label\u003e\n                \u003cinput type=\"text\" name=\"username\" autocomplete=\"off\" class=\"form-control\" value=\"\u003c?php echo $username; ?\u003e\"\u003e\n                \u003cspan class=\"help-block\"\u003e\u003c?php echo $username_err; ?\u003e\u003c/span\u003e\n            \u003c/div\u003e    \n            \u003cdiv class=\"form-group \u003c?php echo (!empty($password_err)) ? 'has-error' : ''; ?\u003e\"\u003e\n                \u003clabel\u003ePassword\u003c/label\u003e\n                \u003cinput type=\"password\" name=\"password\" autocomplete=\"off\" class=\"form-control\"\u003e\n                \u003cspan class=\"help-block\"\u003e\u003c?php echo $password_err; ?\u003e\u003c/span\u003e\n            \u003c/div\u003e\n            \u003cdiv class=\"form-group\"\u003e\n                \u003cinput type=\"submit\" class=\"btn btn-primary\" value=\"Login\"\u003e\n            \u003c/div\u003e\n            \u003cp\u003eDon't have an account? \u003ca href=\"register.php\"\u003eSign up now\u003c/a\u003e.\u003c/p\u003e\n        \u003c/form\u003e\n    \u003c/div\u003e    \n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n### Step 5: Creating the welcome module\n\nHere's the code of our \"welcome.php\" file, where user is redirected after successful login.\n\n```\n\u003c?php\n/* Initialize the session */\nsession_start();\n \n/* Check if the user is logged in, if not then redirect him to login page */\nif(!isset($_SESSION[\"loggedin\"]) || $_SESSION[\"loggedin\"] !== true){\n    header(\"location: login.php\");\n    exit;\n}\n?\u003e\n \n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003eWelcome\u003c/title\u003e\n    \u003clink rel=\"stylesheet\" href=\"assets/bootstrap.css\"\u003e\n    \u003cstyle type=\"text/css\"\u003e\n        body{ font: 14px sans-serif; text-align: center; }\n    \u003c/style\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cdiv class=\"page-header\"\u003e\n        \u003ch1\u003eHi, \u003cb\u003e\u003c?php echo htmlspecialchars($_SESSION[\"username\"]); ?\u003e\u003c/b\u003e. Welcome\u003c/h1\u003e\n    \u003c/div\u003e\n    \u003cp\u003e\n        \u003ca href=\"logout.php\" class=\"btn btn-danger\"\u003eSign Out of Your Account\u003c/a\u003e\n    \u003c/p\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n### Step 6: Creating the logout script\n\nNow, let's create a \"logout.php\" file. When the user clicks on the log out or sign out link, the script inside this file destroys the session and redirect the user back to the login page.\n\n```\n\u003c?php\n/* Initialize the session */\nsession_start();\n \n/* Unset all of the session variables */\n$_SESSION = array();\n \n/* Destroy the session */\nsession_destroy();\n \n/* Redirect to login page */\nheader(\"location: login.php\");\nexit;\n?\u003e\n```\n\n## Sql Injection Execution Approach\n\nSQL injections are one of the most common vulnerabilities found in web applications nowadays. \nI will explain what a SQL injection attack is and take a look at an example of a simple vulnerable PHP web \napplication accessing a MySQL database. After that, we will look at several methods to prevent this attack, \nfixing the problem.\n\nAs we have already set up our php simple web application now we will try to attach on the developed web application.\nUsually username and password is required to access dashboard (welcome.php) but we will enter following code in username text field and \nany password you can enter which will not validated while login.\n```\n' or 1 = 1 -- '\n```\nIn backend php code will create sql query in the following way.\n```\nSELECT id, username, password FROM users WHERE username = '' or 1 = 1 -- '' and password = md5('123')\n```\nIn where clause username field has null value but after that there is or condition which says 1 = 1 that is always true. \nAfter or condition there is (--) comment symbols which ignore the rest of the sql where clause. \n\nSQL Injection code may change as per the php writen code for sql query in single quotation or double quotation.\n\n## Screenshots\n\n### Registration\n![Registration](https://raw.github.com/inforkgodara/sql-injection/master/screenshots/registration.png?raw=true \"Registration\")\n\n### Login\n![Login](https://raw.github.com/inforkgodara/sql-injection/master/screenshots/login.png?raw=true \"Login\")\n\n### Sql where clause code in username field\n![SQL code](https://raw.github.com/inforkgodara/sql-injection/master/screenshots/sql-where-clause-code-in-username-field.png?raw=true \"SQL where clause code\")\n\n### Dashboard\n![Dashboard](https://raw.github.com/inforkgodara/sql-injection/master/screenshots/dashboard.png?raw=true \"Dashboard\")\n\n### MySQL Database Query\n![MySQL Database Query](https://raw.github.com/inforkgodara/sql-injection/master/screenshots/mysql-database-query.png?raw=true \"Database\")\n\n## How to avoid sql injection \n\n* Use prepared statements and parameterized queries\n* Use PHP frameworks (Symfony, Laravel, Codeigniter, CakePhp and etc.) in which already used prepared statements.\n\n## Detailed Video\n* Video clip on demonstration: https://youtu.be/KH_4s2WVDK0\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finforkgodara%2Fsql-injection","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Finforkgodara%2Fsql-injection","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finforkgodara%2Fsql-injection/lists"}