0

I am using MySQLi to prevent any further attacks to my website. I am using PHP 5.6.16, MySQL version of: 5.7.9, and using WAMP

I'm encountering the following error when searching for the user with some weird characters, like adding a ') character in the search box.

MySQL error # 1064 and SQLi vulnerability

How can I sanitize the text box input and prevent any weird or unrecognized characters to be searched?

Screenshot:

Error Screenshoot

Codes:

<?php
# Essential files, please don't erase it!
require_once("../functions.php");
require_once("../db-const.php");
session_start();
?>
<html>
<head>

    <script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
    <h1> View Profile </h1>
<hr />
<?php
if (logged_in() == false) {
echo "<script> window.alert(\"Please login first!\"); </script>";
    redirect_to("login.php");
} else {
    if (isset($_GET['username']) && $_GET['username'] != "") {
        $username = $_GET['username'];
    } else {
        $username = $_SESSION['username'];
    }

    ## connect mysql server
        $mysqli = new mysqli(localhost, root, "", loginsecure);
        # check connection
        if ($mysqli->connect_errno) {
            echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
            exit();
        }
    ## query database
        # fetch data from mysql database
        $sql = "SELECT * FROM users WHERE username ='".$username."' LIMIT 1";

        if ($result = $mysqli->query($sql)) {
            $user = $result->fetch_array();
        } else {
            echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
            exit();
        }

        if ($result->num_rows == 1) {
            # calculating online status
            if (time() - $user['status'] <= (5*200)) { // 300 seconds = 5 minutes timeout
                $status = "Yes";
            } else {
                $status = "No";
            }

            # echo the user profile data
            echo "<title> View Profile of: {$user['username']} </title>";
            echo " Account Searcher: <br>
            <form action=\"?username=\" method=\"get\">
            Unique ID: <input type=\"text\" name=\"username\" placeholder=\"Searching for user: {$_GET['username']}\">
            <input type=\"submit\" value=\"Search\">
            </form><hr>
            ";
            echo "Unique ID: {$user['id']}\n<br>Username: {$user['username']}\n<br>First Name: {$user['first_name']}\n<br>Last Name: {$user['last_name']}\n<br>Email: {$user['email']}\n<br>Online? $status\n<br>";
        } else { // If user doesn't exists - trigger this event
            echo " Account Searcher: <br>
            <form action=\"\" method=\"get\">
            Username: <input type=\"text\" name=\"username\" placeholder=\"User not found!\">
            <input type=\"submit\" value=\"Search\">
            </form><hr>
            ";
            echo "<title> User doesn't exists! | Prospekt </title> <p><b>Error:</b> User doesn't exist! Please register first!</p>";
        }
}

// showing the login & register or logout link
if (logged_in() == true) {
    echo '<a href="../logout.php">Log Out</a> | <a href="../home.php"> Go to Home </a>';
} else {
    echo '<a href="../login.php">Login</a> | <a href="register.php">Register</a>';
}
?>
<hr />
</body>
</html>
user229044
  • 232,980
  • 40
  • 330
  • 338
virtualAnon
  • 141
  • 1
  • 1
  • 12
  • the pdo tag is not needed since none of this code is pdo. It is all mysqli. I do not see where you have the `)`. was the character send through a text box? – Teddy Codes Aug 07 '16 at 05:24
  • Sorry for that :) I just removed the PDO tag and the PDO in to the intro – virtualAnon Aug 07 '16 at 05:26

2 Answers2

0

You are sending the values directly into the database query before validating them which may cause dangers.To prevent sql injections there are inbuilt php functions like mysqli_real_escape_string(). being that said a complete better solution is using Php prepared statements with PDO..

In your code: when you are taking some data from user either from get or post variables do this

<?php

$uname=$_GET['username'];
//now validate
$username=mysqli_real_escape_string($conn,htmlspecialchars($uname));
//Now username is somewhat protected.so now use it for sql queries.

?>
StackB00m
  • 502
  • 1
  • 5
  • 16
0

Your code is vulnerable to SQL injections. The best idea is to parameterize the queries using prepared statements or pdo. Escape the strings too and sanitize them. Learn more about prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

twodee
  • 606
  • 5
  • 24
  • I pretty knew that this codes is vulnerable to SQL Injections, this is more like a _training_ for me cause i'm only 13 years old and a 2nd year highschool students :) thanks for the idea tho – virtualAnon Aug 07 '16 at 06:34
  • I started your age too, we are all in the learning process. Always use prepared statements and use pdo in case you think you will be shifting to other Database programs. @virtualAnon – twodee Aug 07 '16 at 06:36
  • I'm gonna use PDO as soon i'm gonna _"shift"_ to other database programs, i'm only using MySQLi now cause I only got MySQL in my hosting program (which is 000Webhost) [I don't advertise this hosting service] – virtualAnon Aug 07 '16 at 06:39
  • 000Webhost had been hacked earlier and they didn't store passwords in a hashed format. Which teaches you that you should always hash passwords while storing them in the database. For more, check php.net/manual/en/function.password-hash.php, since you are a beginner. – twodee Aug 07 '16 at 06:42
  • I have hashed my password when they're gonna register ;) I've got help from my friend that he taught me how to hash password using SHA256, MD5, and more :) – virtualAnon Aug 07 '16 at 06:45