<?php

// SQL Injection Example - No URL Encoding

// info in world-readable file
$link mysql_connect ("127.0.0.1""was""was");
mysql_select_db("webappsec"$link);


?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>Web Application Security - SQL Injection Example</title>

    <link rel="stylesheet" href="wasexample.css" />
</head>
<body class="example">
    <h1>SQL Injection</h1>

<?php
$username 
"";
$password "";

if( isset( 
$_POST"username" ] ) && isset( $_POST"password" ] ) )
{
    
$username $_POST"username" ];
    
// I can't turn magic quotes off.  Who sucks now?
    
$password stripslashes$_POST"password" ] );

    
// BAD: plaintext password
    
$query "select id from users where username='{$username}' and password='{$password}'";

    
$query_safe sprintf"select id from users where username='%s' and password='%s'"
                            
mysql_real_escape_string$username )
                            , 
mysql_real_escape_string$password ) );

    
$result mysql_query$query );

    echo 
"<div>";
        echo 
"<p class=\"query\"><h4>Sent query:</h4>{$query}</p>";

        echo 
"<p class=\"results\"><h4>Results:</h4>";
        if( 
$result )
        {
                echo 
"<ul>";
            while( 
$user mysql_fetch_object$result ) )
            {
                echo 
"<li>{$user->id}</li>";
            }
                echo 
"</ul>";
        } else {
            echo 
"no results";
        }
        echo 
"</p>";

        echo 
"<p class=\"query\"><h4>Safe query</h4>{$query_safe}</p>";
    echo 
"</div>";
}

?>

    <form method="post">
        <dl>
            <dt><label for="username">Username:</label></dt>
            <dd><input type="text" name="username" value="<?php echo $username?>" size="20" /></dd>

            <dt><label for="password">Password:</label></dt>
            <dd><input type="text" name="password" size="60" value="<?php echo $password?>" /></dd>

            <dt><input type="submit" value="login" /></dt>
        </dl>
    </form>
    
    <ul>
        <li>' or password&lt;&gt;'</li>
        <li>' or '1'='1</li>
        <li>a' or ( 1=1 and username = (select username from users limit 1))#</li>
        <li>; update users set email = 'rob.drimmie@gmail.com'; #</li>
        <li>; drop table users #</li>
        <li></li>
    </ul>
</body>
</html>