0

The script below is a script I¨ve found online, which should be Sql Injection safe. Id like someone to confirm this. My main question in this post is, how can I get this script XSS safe in the same script?

In the end of my post I've added a PHP script that should prevent XSS. But I dont know how I should write that XSS function within this anti-sql-injection script.

if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password);
        $stmt->fetch();
        // Account exists, verify the password.
        if ($_POST['password'] === $password) { // Ikke Kryptert
            session_regenerate_id();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['id'] = $id;
            echo 'Welcome ' . $_SESSION['name'] . '!';
        } else {
            // Incorrect password
            echo 'Incorrect username and/or password!';
        }
    } else {
        // Incorrect username
        echo 'Incorrect username and/or password!';
    }

Before I learned I need to prevent SQL injection with a code as the one above, I've only used my login script like this.

function valid($info) {
        $info = htmlspecialchars($info);
        $info = trim($info); 
        $info = stripslashes($info);
        return $info;
}

$username = valid($_POST['username']);

or

$_SESSION['name'] = valid($_POST['username']);

How can I write my script so that it is both Sql-injection safe, and XSS safe in the same login script?

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
want2lrn
  • 1
  • 1
  • 1
    I can understand you're looking for help, but when it comes to security you shouldn't rely on what other people tell you is safe: You should **understand yourself** why something is safe or not. This is true for SQL-injection and for [XSS](https://www.cloudways.com/blog/prevent-xss-in-php/). Test your code, does it do what you think it should do? In the end you're responsible for your code, and nobody else. – KIKO Software Sep 02 '23 at 18:23
  • I would also look into password_hash to secure the passwords as well. – Nigel Ren Sep 02 '23 at 18:35
  • 1
    **WARNING** Stop using `valid()` function as it will damage your data! This is not a valid protection against SQL injection or XSS! – Dharman Sep 02 '23 at 18:44
  • SQL injection and XSS have nothing to do with each other. SQL injection is when you build SQL queries dynamically and you allow variable input. XSS is when you output data into HTML or similar medium. – Dharman Sep 02 '23 at 18:46

0 Answers0