开发者

PHP - Checking for session in HTML page

I have an HTML page that I do not want to be available unless the login is successful. My login starts a session, however I don't know how to check for the session in the HTML and if the session exists I want to 开发者_运维技巧display the page, if not I want to display a unauthorised message. How can I do this?


You can't check for the session in the HTML per se you'd have to do it in PHP. Depending on how your page is built using PHP you could try putting something like this at the top of your HTML file:

<?php
if (!isset($_SESSION['my_login_var'])) {
  echo 'Unauthorised';
  exit();
}
?>

But you'd be far better off doing this earlier on in your PHP code, in which case you could use the header function to send the user to a proper 403 page.

UPDATE

Usually PHP does some processing before the HTML is outputted and the headers are sent to the connecting client, so you want to send a 403 header before that output happens. This could be in an included PHP file that is run before the HTML is built, or even in the HTML file itself if no other content has been outputted before the script reaches that point.

You can make a small adjustment to the code above to send a 403 header and 'properly' deny access to the page:

<?php
if (!isset($_SESSION['my_login_var'])) {
  header('HTTP/1.1 403 Forbidden');
  exit();
}
?>


You're going to need to look up PHP sessions. See http://us.php.net/manual/en/function.session-start.php for PHP session_start() documentation.

Basically you will need to do session_start(). If the login is successful, set a session variable like $_SESSION['logged_in'] = true;. Then do some logic on your page and redirect/display message depending on the result.

You should attempt something and come back and ask a more specific question if you have problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜