lundi 8 janvier 2018

Preventing specific webpagefrom being accessed directly when no user is logged in php

this is probably a question asked here but i couldn't find it. maybe it was asked differently. i am new in php and am learning sessions. as per what i understand is session variable can be used to prevent certain pages from being accessed if a variable condition is or isnot met. however trying to implement this on my practice project i dont see it really working. i have 3 php pages on my practical project. i copied the code from w3shool. the pages are Index.php, session.php and destroy.php.

the codes are as below for each page.

Index.php

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
<a href="check.php">go</a>
</body>
</html>

check.php

<?php
    session_start();
//check if a session variable exist
if((!isset($_SESSION['favcolor'])) || (!isset($_SESSION['favanimal']))){
    echo "variables not set";
    header("refresh:3; url= index.php");
}
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
<br> <a href="destroy.php">unset</a>
</body>
</html>

destroy.php

<?php
// remove all session variables
session_unset(); 
// destroy the session and go to home
header("refresh:0; url= index.php");
?>

the problem is..after browsing through index, check and finally destroy, when i type check.php in my address bar..it loads the page with the variable intacts. What am i not doing right? i want to use this technique to prevent a page from being loaded if a variable is not true..i.e a profile page wont be loaded if user isnt logged in. if there is a different technique for this, please show with a sample code.

Aucun commentaire:

Enregistrer un commentaire