How can I make sure that only registered users can access the page?

I'm really struggling with the whole "only registered users can view this page". Php is new to me and I cannot figure it out. It might be a stupid question, or my code is wrong, but I'm really trying to figure it out.

login.php:

    <?php
    session_start();

    function is_logged() {
        if (isset($_SESSION['username'])) return $_SESSION['username'];
        else return false;
    }

    if (is_logged()) {
        $user_id = is_logged();

        do_something($user_id);
    } else {
        if (isset($_POST['submit'])) { //form submitted
            //check login and password, if they are correct, do this:
            $_SESSION['username'] = $username_from_database;
            //if not correct
            unset($_SESSION['username']);

            header('Location: welcome.php'); //refresh page
        } else {
            //show login form with button named 'submit'
        }
    }
?>



<html>
<head>
    <title>Login</title>
</head>
<body>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />

        <input type="submit" name="submit" value="Login" />
    </form>
<?php
} else {
    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }

    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT * from GEBRUIKERS WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) {
        echo "<p>Invalid username/password combination</p>";
    } else {
        echo "<p>Logged in successfully</p>";
        // do stuffs
    }



    if (mysqli_num_rows($result) > 0) {
    // Output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $_SESSION['+login_user']=$user; // Initializing Session
        header("location: welcome.php"); // Redirecting To Other Page
    }
} 


else {
    $error = "Username or Password is invalid";
}

mysqli_close($conn); // Closing Connection

}
?>      
</body>
</html>

      

Welcome.php:

<?php
session_start();

?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
<!--Header wordt opgehaald-->
</head>
<?php
    require "header2.php"
?>

<?php   
$servername =   "localhost";
$username   =   ""; 
$password   =   "";
$database = "";
//  Create  connection  
$conn   =   mysqli_connect($servername, $username,  $password, $database);  
//  Check   connection  
if  (!$conn)    {   
                die("Connection failed: "   .   mysqli_connect_error());    
}   
echo "Connected successfully";
?>

<body>

<?php   
//Perform queries
$sql = "SELECT acteur_voornaam, acteur_tussenvoegsel, acteur_achternaam, acteur_geboortedatum FROM FILM_ACTEURS";
$result = $conn->query($sql);
//Films
if ($result->num_rows > 0) {
    echo "<table style='border: solid 1px grey; margin-left: auto; margin-right: auto; margin-top:50px;'><th>Voornaam</th><th>Tussenvoegsel</th><th>Achternaam</th><th>Geboortedatum</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["acteur_voornaam"] . "<td>" . $row["acteur_tussenvoegsel"]. "<td> " . $row["acteur_achternaam"]. "<td> " . $row["acteur_geboortedatum"] . "" . "</td></tr>";
    }
        echo "<table>";
} else {
    echo "0 results";
}

$conn->close();
?> 
    </body>
    <?php
//Footer wordt opgehaald

    include "footer.php"

?>


    </html>

      

+3


source to share


4 answers


session_start (); and checking with is_logged (); should be included in all member-only pages, there is another reason your code is not working and you are not clearing the session variable after you log out, so your browser will automatically register you



0


source


Within your login function, create a session variable in a successful login block like:

$_SESSION['loggedIn'] = true;

      

Now on every page where login is required to access the page, do the following check:



if( !isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn'] != true) )
{
    // redirect the user to login screen if the session variable is not set and its value is not true
    header('location: login.php');
}

      

Note. ... To access the session, you have to put session_start()

on every page, and this must be the first line.

0


source


First create a page titled session.php

which you must include in all pages

<?php
    session_start();

    function is_logged() {
        if (isset($_SESSION['username'])) return $_SESSION['username'];
        else return false;
    }

    if (is_logged()) {
        $user_id = is_logged();

        do_something($user_id);
    } else {
        if (isset($_POST['submit'])) { //form submitted
            //check login and password, if they are correct, do this:
            $_SESSION['username'] = $username_from_database;
            //if not correct
            unset($_SESSION['username']);

            header('Location: welcome.php'); //refresh page
        } else {
            //show login form with button named 'submit'
        }
    }
?>

      

Second: include a page session.php

on all pages. This will validate the session or redirect to the login page.

on the welcome page: Welcome.php

at the top of the page enter session.php

as:

<?php
inlcude 'session.php';
?>

      

Change the file as needed session.php

.

NOTE: you can specify any name in the file session.php

.

0


source


Try using isset function in php. enter the following code after starting your session in welcome.php file.

if(!(isset($_SESSION['username']) && $_SESSION['username'] != '')){
    header ("Location: login.php");
}else{
    header ("Location: welcome.php");
}

      

This is a redirect to the login page if no username session has been established. if the session is already initialized, redirect to a .php greeting.

0


source







All Articles