Session id and variables in PHP

I have a login page where, as soon as the user has successfully logged in, he sends a link to his personal page. When this page loads, I want it to check if the user has access to it, so someone is not trying to simply enter www.mywebsite.com/bob.php in the URL. I tried using a cookie to send user information, but I realized that you cannot use cookies after html has been written to the page. Does anyone know an effective way to do this, which is also pretty simple? Thanks

+3
source share
2 answers

After the user logs in, assign your session variable identifier:

<?php
session_start();
$_SESSION["userid"] = $userid;
?>

On the secure page, check if the user has the variable $ _SESSION ["userid"]:

<?php
session_start();
if (isset($_SESSION["userid"])) {
   //show page
}else{
  echo "No rights";
}
?>
+4
source

It is true that you cannot set cookies when the output is already sent to the browser. A useful trick is to use output buffering . Basically, you start your code with a call ob_start()and end it with ob_end_flush(). Now you can set cookies (and any HTML header) wherever you want in your code.

+1
source

All Articles