user10311677
user10311677

Reputation:

Make page inaccessible if username / password is not typed. PHP

Well, I know there is pluenty of threads like this. But I've tried EVERYTHING they said in the comments without any results. So I guess I've to try it out here...

Bascially, I've a login form at "Login.html" where you type "Username(Name=userId)" and "Password" and that will redirect you to "Login.php" to make sure username and password is written, if it is, it should redirect you again, but to "hidden.php".. And that works fine if I remove

<?php
session_start();
if(!isset($_SESSION['User']))
{
   header('location: login.php');
   exit();
}
?>

This line from the top of "hidden.php".

But on the other side, if people just enter "/hidden.php" without typing password, it should redirect you to "Login.php" which is not working by any reason.. And I've searched a lot and found threads about it, but none of them is actually working in my case.

<?php
    session_start();

    $serverName = "den1.mysql2.gear.host";
    $username = "lexidatabaseweb";
    $password =  "*";
    $db = "lexidatabaseweb";

    //Create connection
    $conn = mysqli_connect($serverName, $username, $password, $db);

    if(isset($_POST['userId']))
{
    $User=$_POST['userId'];
    $Pass=$_POST['passId'];

    $sql = "SELECT * from tbl_register WHERE Username= '".$User."' AND Password = '".$Pass."' limit 1";
    $result = mysqli_query($conn, $sql);

    if(mysqli_num_rows($result) == 1){
        header('location: hidden.php');
        exit();
    }
    else{
        echo" <label style='color:red;'> Wrong username / password.</label>";
        exit();
    }
}
else
{
    echo "Invalid request";
}

?>

The code you can see above is from "Login.php"

Upvotes: 0

Views: 99

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

You do not set the SESSION variable in your login page, so set it once the check is OK....

if(mysqli_num_rows($result) == 1){
    $_SESSION['User'] = $User;
    header('location: hidden.php');
    exit();
}

You should also change the password processing and read about password_hash()

Also look into prepared statements.

Upvotes: 2

Related Questions