It gives me always Invalid Username or Password what is the problem with this code ?

<form action="admin_login.php" method="POST">
                    <div class="form-group" style="width: 280px;">
                        <label for="usr">Username</label>
                        <input type="text" class="form-control" name="userbox" id="user">
                        <br>
                        <label for="pass">Password</label>
                        <input type="password" class="form-control" name="passbox" id="pass">
                        <br>
                        <button type="submit" name="login" class="btn btn-success">Log In</button>
                    </div>
                    <?php
                        if(isset($_POST["login"])) {
                            $user = $_POST["userbox"];
                            $pass = password_encrypt($_POST["passbox"]);

                            $sql =  "SELECT `ID` FROM `admins` WHERE `username`='".$user."' AND `password`='".$pass."'";
                            $result = $conn->query($sql);

                            if(!$result) {
                                echo "There is problem with connection try again later.";
                                trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
                            } else {
                                if($result->num_rows > 0) {
                                    $row = $result->fetch_assoc();
                                    $_SESSION['admin_id'] = $row['ID'];
                                    header('Location: admin.php');
                                } else {
                                    $_SESSION['admin_id'] = '';
                                    ?>
                                        <li>Invalid Username or Password</li>
                                        <a href="#">Forgot your password?</a>
                                    <?php
                                }
                            }
                            //mysqli_close($conn);
                        }
                    ?>
                </form>

**Password encrypt**

function password_encrypt($password) {
        $hash_format = "$2y$10$";
        $salt_lenght = 22;

        $salt = generate_salt($salt_lenght);
        $format_and_salt = $hash_format . $salt_lenght;
        $hash = crypt($password, "e5h8g7ghe58g7e5hg8e57he58h7j10jxd");
        return $hash;
    }

    function generate_salt($lenght) {
        $unique_random_string = md5(uniqid(mt_rand(), true));
        $base64_string = base64_encode($unique_random_string);
        $modified_base64_string = str_replace('+', '.', $base64_string);
        $salt = substr($modified_base64_string, 0, $lenght);
        return $salt;
    }

    function password_check($password, $existing_hash) {
        $hash = crypt($password, $existing_hash);
        if($hash === $existing_hash) {
            return true;
        } else {
            return false;
        }
    }

Also i want to ask does this code is secure to use and can i put even more security ?

While I can't find where you populated your database the answer to secure is maybe not.

I can't see where you sanitized the user input. That is, what if they put in SQL code in the user name. Do you remember Bobby Drop Tables?
https://www.explainxkcd.com/wiki/index.php/Little_Bobby_Tables explains it.

I worry about SQL injections on this one.

As to why it doesn't work I don't see the rest of the system but for now why not echo whether it's the password or the name failure?

now is updated with the HTML code BTW when i added the password_encrypt function it started to not log me in the admin.php. Also here is the register code and it works good.

<form action="admin_login.php" method="POST">
            <div class= "col-md-12">
                <div class="modal-body">
                    <br>
                    <label>Username</label>
                    <p><input type="text" id="register-username" class="form-control" name="username" /></p>
                    <label>Password</label>
                    <p><input type="password" id="register-password" class="form-control" name="password" /></p>                            <div id="register-message"></div>
                    <?php
                        if(isset($_POST["register"])) {
                            $user = $_POST["username"];
                            $pass = password_encrypt($_POST["password"]);
                            //$tac = $_POST["tac"];

                            /* USER LOCATION */
                            /*$cost = 10;
                            $user_ip = getenv('REMOTE_ADDR');
                            $geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
                            $country = $geo["geoplugin_countryName"];*/

                            if(!empty($user) || !empty($pass)) {
                                $sql = "SELECT `username` FROM `admins` WHERE `username`='".$user."'";
                                $result = $conn->query($sql);

                                if(!$result) {
                                    echo "Database connection failed, try again in few seconds..";
                                    trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
                                } else {
                                    if($result->num_rows >= 1) {
                                        echo "Email or Username already exist, try something else.";
                                    } else {
                                        $sql = "INSERT INTO `admins` VALUES ('', '".$user."', '".$pass."')";
                                        $result = $conn->query($sql);
                                        if($result === false) {
                                            echo "Database connection failed, try again in few seconds...";
                                        } else {
                                            $last_inserted_id = $conn->insert_id;
                                            $affected_rows = $conn->affected_rows;
                                            //exit(header("Location: index.php"));
                                        }
                                    }
                                }
                            }else {
                                echo "<div id='reg_error'>All fields are required!</div>";
                            }
                        }
                    ?>
                </div>
                <div class="modal-footer">
                    <div class="col-md-12">
                        <button type="submit" name="register" class="btn btn-success">Register</button>
                    </div>
                </div>
            </div>
            </form>

You know about SQL injection so you will think that over.

As to the fail, you need to break it down to if it's the username (unlikely) or the password failing.

I can't see your database but most only allow characters so check your encryptor code that it only goes from character to characters allows for the column you are storing in.

I checked them like this:

if($pass != $_POST['passbox']) {
?>
<li>Invalid pass</li>
<?php
} else if ($user != $_POST['userbox']) {
?>
<li>Invalid user</li>
<?php
}

Its giving me that the pass is invalid

In your top post you wrote:
$sql = "SELECTIDFROMadminsWHEREusername='".$user."' ANDpassword='".$pass."'";

Which reads to me you don't get feedback if it's the username or password that failed.

If this was me I'd examine the $pass from that line and my database entry to see if it's the encryption that failed or the username didn't match. That line of code doesn't lend itself to debugging yet.

I removed the password line from the sql and its working just with username

That narrows it down to your password routine. I'm not privy to your SQL system but my suspect is that the encryption may product characters that can't be stored so you can test that by encryption a password (try "password") and then seeing the result from the encrypt function and what is in the database for that user.

Hello Stefan
First of all NO , this code is NOT safe. As rproffitt mentioned it is wide open to SQL injection , take a moment to look at PDO and prepared statements. Then there is the way you encrypt the password , take a moment to look at CRYPT_BLOWFISH , I could you provide you a class that do the job if you would like.
Then I started reading your code and you lost me big, first you write:

function password_encrypt($password) {
        $hash_format = "$2y$10$";
        $salt_lenght = 22;
        $salt = generate_salt($salt_lenght);
        $format_and_salt = $hash_format . $salt_lenght;
        $hash = crypt($password, "e5h8g7ghe58g7e5hg8e57he58h7j10jxd");
        return $hash;
    }

Why are you doing all that with the salt and $format_and_salt variable if you are NOT going to use it ?

Then when you write $pass = password_encrypt($_POST["password"]); and you create a query based on that. The normal way to validate a password that is encrypted against a user input is using the encrypted password , not the other way arround (I could give you an example if you like).

commented: Any time I see an input string used in a SQL statement, I think of Little Bobby Drop Tables. +10

Just to correct my previous post term , of course it is not encryption (blowfish and all crypt results) it is hashing.

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.