-5

I am creating a website for a uni assignment.. I have a remember me button and all that good stuff but Someone looked over my code and said that SQL injection could take place..

what would be the best course of action?

I just need guidance:

<?php 
    include 'functions.php';

    if (loggedin())
    {
        header("Location: index.php");
        exit();
    }

    if (isset($_POST['login']))
    {
        $username = $_POST['username']; 
        $password = $_POST['password'];

        if (isset($_POST['rememberme']))
        {
            $rememberme = $_POST['rememberme'];
        }

        if ($username && $password)
        {
            $login = mysql_query("SELECT * FROM users WHERE username='$username'");

            while($row = mysql_fetch_assoc($login))
            {
                $db_password = $row['password'];

                if($password == $db_password)
                {
                    $loginok = TRUE;
                }
                else
                {
                    $loginok = FALSE;
                }

                if ($loginok == TRUE)
                {   
                    if($rememberme == "on")
                    {
                        setcookie("username", $username, time() + 7200);
                    }
                    else
                    {
                        if ($rememberme == "")
                        {
                            $_SESSION['username'] = $username;
                        }
                    }

                    header("Location: index.php"); 
                    exit();
                }
Kamiccolo
  • 7,758
  • 3
  • 34
  • 47
  • 1
    http://bobby-tables.com/php.html – Brian Glaz Apr 29 '14 at 18:57
  • 1
    Don't use the `mysql_` extensions - use `mysqli` or PDO and use prepared statements. That's the short answer to get you googling - also look at this question/answer - http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – ajtrichards Apr 29 '14 at 18:57
  • Start here: http://www.php.net/manual/en/security.database.sql-injection.php The short answer is that directly concatenating user input into a SQL query is treating that input as *executable code*, hence the SQL injection vulnerability. Never treat user input as executable code. Treat it only as data values. – David Apr 29 '14 at 18:57
  • You can find PDO_MYSQL – Adem Öztaş Apr 29 '14 at 18:57

1 Answers1

-4

there is a php method called addslashes() that will automatically add escape sequences to any string that should handle minor SQL injection attempts

sgrutman978
  • 114
  • 8