Hey guys,

Could you help me understand how to implement

mysql_real_escape_string

to prevent injection in this code ?

<?php

    if(loggedin()){
        echo "You are already logged in.";
    } else {
        if($_POST['submit']){
            if($_POST['username'] && $_POST['password']) {
                $username = $_POST['username'];
                $password = $_POST['password'];
                $password = md5($password);
                $res = mysql_query("SELECT * FROM users WHERE username='$username'");
                if(mysql_num_rows($res) == 0){
                    echo "Utilizator inexistent, click <a href='index.php?act=register'>aici</a> pentru inregistrare.";
                    exit();
                }
                $row = mysql_fetch_assoc($res);
                if($row['password'] == $password) {
                    if(@$_POST['remember' == "on"]) {
                        setcookie('username', $username,time()+36000);
                        echo "You have been logged in,<a href='index.php'>click here</a> to continue.";
                    } else {
                        $_SESSION['username'] = $username;
                        echo "You have been logged in,<a href='index.php'>click here</a> to continue.";
                    }
                } else {
                    echo "Incorrect password.";
                }
            }
        } else {
            
      
?>

Recommended Answers

All 5 Replies

Member Avatar for diafol
$username = mysql_real_escape_string($_POST['username']);

Because you're hashing the pw before it is used in any mysql, perhaps mysql_real_escape_string not so impt for this field. However, every other field should be escaped - even integers. Forms and headers can be spoofed so you can't even rely on what you assume to be your 'own safe values'.

Thank you ardav,

What do you mean by escaping integers as well ? I escaped the password and the username, what else should i escape ?

Member Avatar for diafol

>Thank you ardav,

What do you mean by escaping integers as well ? I escaped the password and the username, what else should i escape ?

You should escape everything - everything that has been touched by an external source (querystring/cookie/form). Clean all variables pasted into an SQL statement. It will not affect numeric data - so it is safe to use.

Thank you for the explanation!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.