MySQL PHP Check IP


#1

Hello !
When i submit my form the code did not perform the “if”, it take the “else”.
Why ?

The code:

    <?php
    // Date MySQL;
    $username = "encodare";
    $password = "***";
    $host = "***";
    $db = "encodare_troll_mc";

    // Conectare MySQL;
    $connect = new mysqli($host, $username, $password, $db);

    // Verific conexiunea;
    if ($connect->connect_error)
        die("Conexiunea cu baza de date a esuat: ".$connnect->connect_error);

    // Daca se conecteaza, executa:
    session_start();
        // Register (register.php)
        if (isset($_POST['Register']))
        {    
            if (!($connect->query("SELECT IP FROM Users WHERE IP = '{$_SERVER["REMOTE_ADDR"]}'")))
            {
                $insert = $connect->prepare("INSERT INTO Users (IP, Username, Age, Email, Password) VALUES (?, ?, ?, ?, ?)");
            $insert->bind_param("sssss", $IP, $Username, $Age, $Email, $Password);
                
            $IP = $_SERVER['REMOTE_ADDR'];
            $Username = $_POST['Username'];
            $Age = $_POST['Age'];
            $Email = $_POST['Email'];
            $Password = $_POST['Password'];
            if(!$insert->execute())
                mysqli_error($connect);
            $_SESSION['succes'] = "Te-ai înregistrat cu succes !\n";
            $_SESSION['succes'] .= "Ai primit un email cu numele de utilizator si parola.";
            header('Location: index.php');
        }
        else
        {
            $_SESSION['error'] = "Esti deja înregistrat.";
            header('Location: index.php');
        }
    }
?>

    <form name="RegisterForm" method="post" style="width: 50%; margin: auto;">
            <input type="hidden" name="Register" value="Register"/>
                        
            <h1 class="frh1">Inregistrare</h1>
                        
            <div class="box">
                <span class="fa fa-user icon"></span>
                <input class="field" type="text" name="Username" placeholder="Ce nume de utilizator doreşti ?" required/>
            </div>
                        
            <div class="box">
                <span class="fa fa-question icon"></span>
            <input class="field" type="text" name="Age" placeholder="Câţi ani ai ?" required/>
        </div>
                    
        <div class="box">
            <span class="fa fa-envelope icon"></span>
            <input class="field" type="text" name="Email" placeholder="Scrie-ne email-ul tău, te rog." required/>
        </div>
                    
        <div class="box">
            <span class="fa fa-lock icon"></span>
            <input class="field" type="password" name="Password" placeholder="Ce parola doreşti ?" required/>
        </div>
                    
        <button class="submit" name="submit">Inregistreaza-ma</button>
                    
    </form>

#2

A SELECT query that executes, but doesn’t match any data is a successful query and returns a mysqli result object. You need to either test the num_rows property of the result object or fetch the row of data.


#4

So… I need to write something like that ?:
$result = $connect->query(“SELECT IP FROM Users WHERE IP = ‘{$_SERVER[“REMOTE_ADDR”]}’”);
$result = $connect->num_rows;
if (num_rows > 0)
//code…

That was after if (!($connect-&gt;query("SELECT IP FROM Users WHERE IP = '{$_SERVER["REMOTE_ADDR"]}'"))) and was the same problem.


#5

You code does not really make sense. You select an IP from your database based on an IP you already have.
Makes no sense at all.

Also, IP’s can be spoofed with ease. It is simple to fake them. So, checking a user’s IP when they log in is not any kind of security.

It would be better to search for their email address because that is not easy to change or fake.

And, lastly, what happens if you have a husband and wife who both want to register on your site from the same computer? They would both have the same IP address. I suggest you think out the logic of the code and try again. Is this for a class?


#6

Yeah, you are right…
I was changed to:
$email = mysqli_real_escape_string($_POST[‘Email’]);
$query = “SELECT Email FROM Users WHERE Email = ‘$email’”;
$results = mysqli_query($connect, $query);
if (mysqli_num_rows($connect, $results) == 0)
{
$insert = $connect->prepare(“INSERT INTO Users (IP, Username, Age, Email, Password) VALUES (?, ?, ?, ?, ?)”);
$insert->bind_param(“sssss”, $IP, $Username, $Age, $Email, $Password);

            $IP = $_SERVER['REMOTE_ADDR'];
            $Username = $_POST['Username'];
            $Age = $_POST['Age'];
            $Email = $email;
            $Password = $_POST['Password'];
            if(!$insert->execute())
                mysqli_error($connect);
            $_SESSION['succes'] = "Te-ai înregistrat cu succes !\n";
            $_SESSION['succes'] .= "Ai primit un email cu numele de utilizator si parola.";
            header('Location: index.php');
        }
        else
        {
            $_SESSION['error'] = "Esti deja înregistrat.";
            header('Location: index.php');
        }

But it still the same, don’t work…


#7

You need to set php’s error_reporting to E_ALL and display_errors to ON, so that php will help you by reporting and displaying all the errors it detects. The last two pieces of code you have posted contain mistakes that php would produce php errors for to help you find the problems.

You need to make use of the php.net documentation. Your use of mysqli_num_rows() is incorrect.

You need to pick one coding style (Procedural or OOP) and consistently use it throughout your code. OOP is shorter and the better choice.

You need to use prepared queries for all queries that supply external/unknown data to the sql query statement.

You should switch to the much simpler php PDO extension.

Lastly, when you run a SELECT query to try to find if data already exists before INSERTing it, multiple concurrent visitors or one visitor submitting the form multiple times can all attempt to insert the same value, resulting in either duplicate rows (if you don’t have the db table set up with unique column(s) defined) or in a query error (if you do properly have the db table set up with unique column(s) defined.)

What you should do instead is just attempt to insert the data and detect if the query produced a duplicate key error. This will result in the simplest code, the fewest queries, and the fastest running application. If you enable exceptions for db statement errors, you would have a try/catch block around the execution of the query, test for the duplicate key error number (it’s 1062), and set up a duplicate email message to display to visitor. If the error number isn’t for a duplicate key, you would re-throw the exception.


#8

Well, this is better.

Change this section:

if(!$insert->execute())
                mysqli_error($connect);

To this:

if(!$insert->execute())
                echo "Error: " . mysqli_error($connect);

and it should show you the error. Also, for testing, you can add these two lines at the top of your code and it will show any other errors on the page:

error_reporting(E_ALL);
ini_set('display_errors', 1);

(Normally, you remove these two lines after testing it done.) Rerun and show us the errors you get.


#9

I solved the problem !
Thank you for help, guys ! :slight_smile: