Check page permission by session? - php

I included header.php to every page for header logo and check page permission by SESSION!
So if you request main.php without login (session null state), It will display login page and do exit in header.php for not showing current page content.
Its header.php is work for every page except login.php.Because login page is not show login form
So I want to show login form ,how can I check in header.php for its ? Sorry for my poor english :(
login.php
<?php
session_start();
include("header.php");
if($_POST){
//set session logged in
}
?>
<div class="login-box ">
<h3> Log In </h3>
<form method="POST">
<input type="text" name="user" placeholder="Type User Name"><br>
<input type="password" name="pass" placeholder="Type Password"><br>
<input type="submit" name="submit" value="Login" class="button">
</form>
<span id="signup_text">You are not still a member.Click Sign Up</span>
</div>
header.php
<?php
session_start();
?>
<div id="header" class="container">
<div id="logo">
<h1>Online Quiz Management</h1>
</div>
</div>
<?php
if (isset($_SESSION['login'])) {
echo "<div id='menu'><ul><li>HOme</li><li>Signout</li></ul></div>";
}
else {
echo "<div class=head1> Your are not logged in<br> Please <a href=login.php>Login</a><div>";
exit;
}
?>
</div>
</div>
?>
main.php
<?php
session_start();
include("header.php");
?>
//show main code if logged in

Just add a check if the current page is login.php and don't run your block if it is
else if(!basename($_SERVER['PHP_SELF']) == "login.php") {
echo "<div class=head1> Your are not logged in<br> Please <a href=login.php>Login</a><div>";
exit;
}

i think u dont need to include the header.php to login.php, since it is check for the session, while the login.php is the session starter...
after all, try to add this to the header.php :
session_start();
if(!isset($_SESSION['login'])){
echo '<script language="javascript">';
echo 'alert("Please Login")';
echo '</script>';
echo("<script>location.href = 'login.php';</script>");//direct the user to login.php if they aren't logged in
}

Related

Changing navigation bar option list after logging in to website

I am trying to build a php login system with no databases being used.
The system is build from 4 main php files, login.php, welcome.php and product.php and logout.php.
in the navigation's bar of other pages, there is a "login" option, when clicking on it you are just being transfered into login.php file that contains the login form.
I want to change the login to logout when getting the right password and username.
here is the code for login.php:
<form method="POST" action="login/welcome.php" class="form">
<h2 class="h2" style="text-align: center;">Login</h2>
<div class="input">
<input type="text" class="form-control" placeholder="username" name="username">
</div>
<br>
<div class="input">
<input type="password" placeholder="password" name="password">
</div>
<br>
<button type="submit" class="float" style="padding: 10px 15px;"><b>Submit</b></button>
</form>
And this is the code for welcome.php:
<?php
$username="admin";
$password="admin";
session_start();
if (isset($_SESSION['username'])){
header("Location: https://chessforu.000webhostapp.com/login/product.php");
}
else{
if ($_POST['username']==$username && $_POST['password']==$password){
$_SESSION['username']=$username;
echo "<script>location.href='welcome.php'</script>";
}
else{
echo "<script>alert('username or password incorrect!')</script>";
echo "<script>location.href='login.php'</script>";
}
}
This is the code for product.php:
<?php
session_start();
if (isset($_SESSION['username'])){
}
else {
echo "<script>location.href='login.php'</script>";
}
<html>
<body>
<p> Thanks for logging in! </p>
<div id="wrapper">
<nav>
<ul class="main_menu">
<li>Main Page
<li>About Us
<li>Contact us
<li>Logout
</ul>
</nav>
</div>
This is the code for logout.php:
<?php
session_start();
if (isset($_SESSION['username'])){
session_destroy();
echo "<script>location.href='login.php'</script>";
}
else{
echo "<script>location.href='login.php'</script>";
}
?>
Just use a simple if statement that determines what button/link to display (log in or log out) by simply checking the session to check if he is logged in or not.
To not repeat yourself, You can move the navigation bar to a single file, add your logic, and require this file whenever you want to add the navigation bar.

Login implementation in PHP

Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>

force login page before index

I have a login form that displays a message when a user either registers or logins in. I would like the login page to open first and after successful login then index.php can be shown. also should someone try and access /index.php directly it must still direct them to login.php to be authenticated. I have tried some examples of other peoples codes but i cannot get the page to authenticate the user.
My Login.php code:
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$sql = "SELECT * FROM `login` WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['username'] = $username;
}else{
$fmsg = "Invalid Username/Password";
}
}
if(isset($_SESSION['username'])){
$smsg = "User already logged in";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Login in PHP & MySQL</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container">
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<form class="form-signin" method="POST">
<h2 class="form-signin-heading">Please Register</h2>
<div class="input-group">
<input type="text" name="username" class="form-control" placeholder="Username" required>
</div>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholde r="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<a class="btn btn-lg btn-primary btn-block" href="register.php">Register</a>
</form>
</div>
</body>
</html>
You can if statement to check whether user is login or not.
If user is not logged in then you can redirect them to login.php
If user is logged in then you can let them see index page.
To do so, code example is given below....
<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
$welcomeMessage = "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
header('Location: login.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Index page</title>
</head>
<body>
<?
if(!empty($welcomeMessage)) echo $welcomeMessage;
?>
Index page
</body>
</html>
I would like the login page to open first and after successful login then index.php can be shown.
Well you could create a .htaccess file then add this line:
DirectoryIndex login.php when someone visits your site will go to login.php
then on login.php
first check if that user is not loggedin already
therefore login.php
<?php
session_start();
require_once('connect.php');
if(isset($_SESSION['username'])){
$smsg = "User already logged in";
header("location:index.php"); // send to index if logged in
}else{
// the code you have in your question here
}
?>
also should someone try and access /index.php directly it must still direct them to login.php to be authenticated. You would need to check if the session is set or not if its set continue or send them back to login
index.php
<?php
session_start();
if(isset($_SESSION['username'])):?>
Your html content
<?php
else:
header("location:login.php");//send them to login
endif;
?>
The absolute easiest way (according to me) would be to create a new file called auth.php with the following content:
<?php
session_start();
if (empty($_SESSION['username'])) {
// The username session key does not exist or it's empty.
header('location: /login.php');
exit;
}
Then, in the very top of every page you want to protect (including your index.php), just add:
<?php
require __DIR__ . '/auth.php';
?>
// Continue with your HTML here
No need to build the sites inside if/else-statements.
Note: This assumes that all your pages are in the root folder. If you have other pages in sub folders that you want to protect, you need to add the correct path to auth.php, since __DIR__ gives you the absolute path of the file you write it in.

PHP - refresh entire page from an included file?

At the top of every page I have a header (header.inc.php) that has a login field that I add with
include 'login.php';
The code there is:
<?php
include 'checkPassword.php';
if (isset($_POST['login'])) {
if (checkLogin($_POST['username'], $_POST['password'])) {
session_start();
$_SESSION['isLoggedIn'] = true;
header("Refresh:0");
exit();
} else {
echo '<h1>nope</h1>';
}
}
?>
<div id="login"> <!-- Login field with link to registration -->
<fieldset>
<form method="POST" action="login.php">
<Legend>Login</Legend>
Username <input type="text" name="username" <?php if (isset($username)) {echo "value=$username";} ?>>
Password <input type="password" name="password"/>
<input type="submit" name="login">
<div id="register">
Not a member? Click here to register!
</div>
</form>
</fieldset>
</div>
I've seen a few different methods for using header() to load a certain page, but the login appears at the top of every page, therefore I'd like a way for the PHP to refer to itself. However, all the methods I've found so far refer to 'login.php', instead of the page the overall page that contains the header and login.
try this one
<?php
include 'checkPassword.php';
if (isset($_POST['login'])) {
if (checkLogin($_POST['username'], $_POST['password'])) {
session_start();
$_SESSION['isLoggedIn'] = true;
header("Refresh:0");
exit();
} else {
echo '<h1>nope</h1>';
}
}
?>
It refreshes your current page, and if you need to redirect it to another page, use following:
header("Refresh:0; url=page2.php");
echo meta tag like this: URL is the one where the page should be redirected to after refresh.
echo "<meta http-equiv=\"refresh\" content=\"0;URL=upload.php\">";

Adding Function on Sign Out button by php

I am creating a website where I want to sign in and sing out. So when I sign in I redirect to home.html, so in home.html I added a button by naming it "logout", I want to add function on it so whenever I will click on that button it will sign me out. As I know already, the code I have to use but don't know how put that code to logout button?
I want to know how I can refer my this button name="logout" button to that specific code
session_destroy(); so when I m in home.html click on Sign out button it will destroy my current season and locate me back to index.php.
index.php
<form class="form-horizontal" role="form" action="process.php" method="post">
<div class="form-group">
<label id="email" for="inputtext" class="col-sm-4 control-label">User name:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="inputEmail" placeholder="User name" name="username">
</div>
</div>
<div class="form-group">
<label id="pass" for="inputPassword" class="col-sm-4 control-label">Enter Password</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="pass">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Sign me in!</button>
</div>
</div>
</form>
process.php
<?php
$action = $_GET['action'];
if ($action == 'logout') {
unset($_SESSION['username']);
}
$username = $_POST ['username'];
$password = $_POST ['pass'];
//fixed values
if($username=='syedhasan' AND $password=='Syed712207') {
echo "You have successfully logged in";
header('Location: home.html');
}
else {
echo "Credential is wrong";
}
?>
in home.html i have added this button
<input href="logout.php" type="submit" class="signout btn btn-warning"" value="Sign Out" name="logout">
THen i created logout.php
<?php
session_start();
unset($_SESSION);
session_destroy();
header("Location: index.php");
?>
Create another file named "logout.php".Place the below code.
<?php
session_start();
unset($_SESSION);
session_destroy();
header("Location: index.php");
?>
On click of "logout" button ,it should redirect to "logout.php".
Just create another page called logout.php. Unset the session there unset($_SESSION['someusername']) and write code to redirect to your home page.
header('Location: http://www.example.com/');
All you have to do is give user a link to sign out, and redirect the page to index.php.
home.html:
Logout
logout.php
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
ok
you have logout buttom with and you have to make logout.php and link it to logout buttom
for example
logout.PHP
<?PHP
session_start();
session_destory();
unset($_SESSION['user_id']);
header("location: login.html");
?>
And index.html like this
<a name="logout" href="logout.php"> Logout </a>
I assume your login page is login.php, there I guess you have a html form for username and password, and also have the user validation with the redirect to home.html. It makes sense to put the logout logic also in there.
Put the following code to the top of login.php:
$action = $_GET['action'];
if($action == 'logout') {
/* I'm sure you don't want to destroy the entire session, as there
could be other valuable data stored, so use unset to destroy only
the specific login-variable. */
unset($_SESSION['loginVar']);
}
$_SESSION['loginVar'] is the session var where you users login data is stored.
Now you can use the following href for the logout link / button:
login.php?action=logout
HTML
<a href='index.php?logout=1'>Logout</a>
PHP
if(isset($_GET['logout'))
{
session_destroy();
header('Location:home.php');
}

Categories