Bynd
Bynd

Reputation: 705

php allow access to pages to only logged in users

I have 3 pages have html code similar to just example

<!DOCTYPE html>
<html>
<body>

<div>
html code
</div>

<div>
html code
</div>

<div>
html code
</div>

</body>
</html>

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

Upvotes: 1

Views: 9840

Answers (3)

G.Ashok Kumar
G.Ashok Kumar

Reputation: 1633

You need to use session to do it in PHP, it will be like this.

$_SESSION(id)

You can see some tutorial in google.

Refer the below link http://www.makeitsimple.co.in/PHP_loginexmp.php

Upvotes: -2

Calibur Victorious
Calibur Victorious

Reputation: 638

First, Put in header page this session_start();, Ofcourse the header page is included||required in every php page you have.

Second, When the user Login using your Login page, Put the sessions if his data are valid

<?php
if($user && password_verify($password, $user['password'])){
     $_SESSION['id'] = $user['id'];
}
 ?>

In this one we used his id inside session, Now all you have to do is checking if this session is active, If it is not active, You redirect the visitor using header() to the index||404 page like this

<?php 
if(!isset($_SESSION['id'])){
    die(header("location: 404.php"));
}
?>

and remove the ! for signup & login pages, Since you don't want a logged in user to access the login or register page again.

Third, For logout page, Just put

<?php
session_start();
session_unset();
session_destroy();
header("location: index.php");
exit();
?>

inside it

Upvotes: 4

Piyush Patel
Piyush Patel

Reputation: 1751

This answer assumes that you have 3 php files and not html. You need to save those files as .php if you want to manage this using PHP.

Yes you can manage that using a variable or session.

You can redirect the user if they are not logged in. Or, you can show the part of the text and link only if they are logged in.

<?php 
    if($logged_in) {
?>
  <a href="hidddenpage">Only for logged in users</a>
<?php
    }
?>

Upvotes: 1

Related Questions