What is the proper way to authenticate users? As in, setting a page whereby only logged in users can view?
Does this work?
<?php
session_start();
if(!isset($_SESSION[username]) || empty($_SESSION[username]) || !isset($_SESSION[id]) || empty($_SESSION[id]))
{
session_destroy();
session_unset();
die('You\'re not authorized to view this page!');
}
?>
<?php
echo"Can I freely, and safely write my content here? Will it be properly authenticated with my code above?";
?>
But my question is, if I use the above code, can I freely add my content below the code? And is there any other better way to do this?
I have another code whereby I do a
session_destroy();
header("Location: logout.php");
{and then I echo my content below; where logged in users can see}
But I'm just wondering if, once I do that, does it mean users will not be able to see my content below?
Thanks!
You are correct, but you are a bit verbose in your strategy. Here is a simpler way.
<?php
session_start();
if(empty($_SESSION['username']))
{
echo "Not allowed."; // possible redirect to login page.
exit;
}
//Authenticated stuff here.
To logout, just clear the username.
$_SESSION['username'] = "";
Normally, you don't need to worry about cleaning up the internal PHP session cache. PHP has a periodic script that runs in the background on the server to handle that for you.