I have a form which allows users to enter their data. It then checks these data against a database to see if the user exists. If so, it logs them into a certain page.
I would then like to allow them to log out (such that they no longer have access to that certain page). To this end, I created a "logout.php" document in which I try to clear the login details.
However, having done this, if I try load the login page, it takes me back to the logged in page.
Here is my code (login.php - creating the form and logging the user in):
<?php //Start the Session
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password']))
{
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking if the values exist in the database
$checkLogin = $connection->query("SELECT * FROM users
where (username='$username' && password='$password')");
$numRows = $checkLogin->fetchColumn();
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($numRows >= 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo '<script>window.alert("Invalid Login Credentials")</script>';
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "
";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
echo $username;
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<head>
<title>CodingCyber - Simple Login Script</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="login.php" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="register.php">Signup</a>
<input class="btn register" type="submit" name="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
The "require('connect.php')"; just connects to my MySQL database. This code all seems to run fine, in that it does log users in, once validated. I've just included it for completeness w.r.t. the problem.
As you can see, once logged in it displays text saying "Member's area", with a logout hyperlink.
Here is my logout.php code (which I would like to remove access to the member's area, and take user back to the login page):
<?php
session_start();
$username = '';
$password = '';
$confirmPassword = '';
$email = '';
echo $username;
unset($_POST['username']);
unset($password);
?>
This second bit of code is where, to be honest, I'm really not sure what I'm meant to do to remove the access privileges.
I've looked at a few other questions, but can't seem to find the solution.
Any help would be awesome! Please let me know if there is a similar thread or if you need more information.
Thanks!
Try this:
unset($_SESSION['username']);
It will remove the username variable from the session
You need to destroy the session variables:
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
$url = 'http://example.com';
header( "Location: $url" );
exit();
Related
I am trying to develop a simple login page once login login.php it should show index.php
Below files are in the web directory:
> https://www.myowndomain.com/test/status/login.php
> https://www.myowndomain.com/test/status/auth.php
> https://www.myowndomain.com/test/status/index.php
So when the user enters index.php it checks if the session is created if so it will show index.php if not redirect it to login.php.
If I log in using a valid username and password and click login the PHP file is returning to login.php, not to index.php (Session is created in login.php but when accessing the same on indext.php or auth, session it is blank?
In index.php if I don't include auth.php - The login works fine but doesn't get the session.
login.php:
<?php
include("db.php");
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username']))
{
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking if user existing in the database or not
$query = "SELECT * FROM users WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
echo $rows;
if($rows==1)
{
$_SESSION['username'] = $username;
echo "User in session:" . $username;
header("Location: index.php"); // Redirect user to index.php
}
else
{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}
else
{
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>
</body>
</html>
auth.php:
<?php
include("db.php");
session_start();
$user_check=$_SESSION['username'];
$ses_sql = mysqli_query($con, "SELECT username FROM users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username'];
if(!isset($login_session))
{
header("Location:login.php");
}
?>
What could be wrong here? I have check every bit still issue. Probably someone can recheck my code and tell me the issue? Could it be an issue with the web directory? The files are inside a folder/subfolder/?
Other than the obvious security implications of your code, I don't see anything wrong with it. You could try manually setting the session save location. I've found with some hosting that the session path needs to be explicitly set for sessions to work...
session_save_path("/location/to/save/sessions/");
To find out what your session save path should be, contact your hosting provider. If you are using localhost - a quick google will do it.
We have a session logout script like:
<?php
//24 2 2015
session_start();
session_destroy();
header("location:login.php")
?>
now this script logouts and redirect it to login page where, username and password will be required to login again.
what if i wanted to have a temporary logout where after logging out it will direct us to a login page where it will only require password, cause session hasn't been destroyed and username is been passed to that page...
so, when you enter the password, it will check the input in database table where username = session username.
Hope i was clear.
The update::
templogout.php
<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:templogin.php")
?>
templogin.php
<?php
//24 2 2015
session_start();
?>
<form id="msform" action="templogincheck.php" method="post">
<fieldset>
<input type="password" name="password" placeholder="Enter password here" required />
<button type="submit" name="submit" class="submit action-button"> LogIn </button>
</form>
templogincheck.php
<?php
//15 2 2015
session_start();
$Cser =mysqli_connect("localhost","text","text","text") or die("Server connection failed : ".mysqli_error($Cser));
$password = md5($_REQUEST["password"]);
$mobile = $_SESSION['mobile'];
$s = "select * from users where password = '".$password."' and mobile = '".$mobile."'";
$result = mysqli_query($Cser,$s);
$count = mysqli_num_rows($result);
if($count>0)
{
$_SESSION["mobile"] = $mobile;
$_SESSION["login"]="1";
header("location:/index.php");
}
else
{
header("location:/templogin.php");
}
?>
index.php
<?php
//15 2 2015
session_start();
unset($_SESSION["temp_logout"]);
if(!isset($_SESSION["login"]))
header("location:login.php");
?>
I hope i did it right, but i have to presume i have something wrong cause it isn't working..
Am i passing the session mobile to the login check page?
user first login page:
<form id="msform" action="ulogincheck.php" method="post">
<fieldset>
<h2 class="fs-title">LogIn</h2>
<h3 class="fs-subtitle">Please Enter your details accordingly<br/><br/> <small>(case sensitive)</small></h3>
<input type="text" name="email" placeholder="Email" required />
<input type="text" name="mobile" placeholder="Mobile" required />
<input type="password" name="password" placeholder="Password" required />
<button type="submit" name="submit" class="submit action-button"> LogIn </button>
</form>
first logincheck page
session_start();
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$password = md5($_REQUEST["password"]);
$s = "select * from users where email='".$email."' and password = '".$password."' and mobile = '".$mobile."'";
$result = mysqli_query($Cser,$s);
$count = mysqli_num_rows($result);
if($count>0)
{
$_SESSION["email"] = $email;
$_SESSION["mobile"] = $mobile;
$_SESSION["login"]="1";
header("location:/index2.php");
}
else
{
header("location:/usersignin.php");
You could add a "temp_logout" field to the $_SESSION variable and when you redirect the user to the login page, you can check for it $_SESSION["temp_logout"] and if it is true, add the username in the input field.
logout script:
<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:login.php")
?>
login page:
session_start()
...
//where the "username" input is
<input name="username" <?php if(isset($_SESSION["temp_logout"]){
echo 'value="'.$_SESSION["username"] .'" ';
} ?> />
...
after a successfull login:
<?php
session_start();
unset($_SESSION["temp_logout"]);
?>
Also, anywhere on the site, don't forget to check if the user is temporarily logged out; then immediatelly redirect him to the login page
it is really depend on your platform:
You can only unset something like password instead of destroying session,
unset($_SESSION['password']);
or set another key in session:
$_SESSION['loggedIn'] = false;
and redirect to login page.
also you can put username in cookie and destroy session.
setcookie
If you want to store username in cookie it is better to encrypt it for security reasons.
I am struggling with this login system. What I am trying to accomplish is an admin area, platinum area and a gold area. When the script is run it logs in the user but it lands on a white screen. Using my browser's back button I can then get to the index and select the url I am trying to access and I am logged in. When I log out sometimes I can still access the pages but the session is lost as it should be. I should be directed to logon again but I am not.
The script below I named admincontrol.php
<?php
session_start();
$_SESSION['auth'] = "OKAY";
//error_reporting(E_ALL);
if (isset($_POST['username']))
{ $username = isset($_POST['username']) ? $_POST['username'] : $_SESSION['username'];}
$level = (isset($_POST['level']) ? $_POST['level'] : (isset($_SESSION['level']) ? $_SESSION['level'] : 'nolevel'));
$pwd = (isset($_POST['pwd']) ? $_POST['pwd'] : (isset($_SESSION['pwd']) ? $_SESSION['pwd'] : 'nopwd'));
if(empty($username)) {
?>
<!doctype html>
<head>
<title> Please Log In for Access</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<div align="center">
<img src="../images/alls.gif">
<h1 align="center"> <font face="Arial, Helvetica, sans-serif">Login Required
</font></h1>
<p align="center"><font face="Arial, Helvetica, sans-serif">You must log into access this area of the site. <br />
</font></p></div>
<div align="center">
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<font face="Arial, Helvetica, sans-serif">User ID:
<input type="text" name="username" size="8" />
<br />
Password:
<input type="password" name="pwd" SIZE="8" />
<br />
<br />Select your title from the drop down
<select name="level">
<option value="1">Platinum</option>
<option value="2">Gold</option>
<option value="0">Admin</option>
</select>
<br /><br />
<br /><br />
<input type="submit" value="Log in" />
</p>
</font></form></div>
</body>
</html>
<?php exit;
}
$pwd = md5($pwd);
$_SESSION['username'] = $username;
$_SESSION['pwd'] = $pwd;
$_SESSION['level'] = $level;// 0 = Admin, 1 = institutional subscriber, 2 = individual subscriber
include_once 'db.php';
//allows user to access specific page only!
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$pwd' AND level = '$level'";
$result = mysql_query($sql);
if (!$result) {
error('A database error occurred while checking your '.
'login details.\\nIf this error persists, please '.
'contact me#my.com. ');
}
if (mysql_num_rows($result) == 0) {
unset($_SESSION['username']);
unset($_SESSION['pwd']);
unset($_SESSION['level']);
?>
<!doctype html>
<html>
<head>
<style type="text/css">
body{font-family:Arial, Helvetica, sans-serif}
</style>
<title>Access Denied Admin</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<center>
<body>
<h1> Access Denied </h1>
<p>Your user ID or password or Title are incorrect, or you are not a registered user on this site.</p>
<p>Try logging in again.</p>
</font>
</body></center>
</html>
<?php
exit;
}
?>
I am using this code for my pages that I need controlled
<?php
session_start();
if(!isset($_SESSION['auth']))
{
include("admincontrol.php");
}
?>
Here is logout.php
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
if(!isset($_SESSION['auth']))
{
header("Location: admincontrol.php");
}
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
<meta http-equiv="refresh" content="1;URL=individual-level-test.php">`
You have other issues apart from when you're setting the OKAY session variable.
For example:
if (isset($_POST['username']))
{
$username = isset($_POST['username']) ? $_POST['username'] : $_SESSION['username'];
}
You're checking whether the POST value "username" exists and then setting the username variable based on whether the POST value "username" exists with a fallback to the SESSION value "username".
This is redundant code and has the following knock-on effect as follows.
if(empty($username)) {}
Your username check will always return true for empty() when using this on a secondary page (once you're logged in) and present you with the log on form.
Also your password fallback
$pwd = (isset($_POST['pwd']) ? $_POST['pwd'] : (isset($_SESSION['pwd']) ? $_SESSION['pwd'] : 'nopwd'));
$pwd = md5($pwd);
Any session password will already be in md5 format, so your database call will fail and present the "Access Denied" screen. Use the md5 function around the $_POST rather than later on in the code to prevent this from happening like this:
$pwd = (isset($_POST['pwd']) ? md5($_POST['pwd']) : (isset($_SESSION['pwd']) ? $_SESSION['pwd'] : 'nopwd'));
And lastly, you're creating a database call checking the user exists for every time you use admincontrol.php, even once you're logged in on secondary pages. You're storing the user details in SESSION anyway - why have extra db calls when you don't need them.
I figured it out, I was calling
$_SESSION['auth'] = "OKAY";
too soon!
It needed to be placed with the other session variables like this
$_SESSION['username'] = $username;
$_SESSION['pwd'] = $pwd;
$_SESSION['level'] = $level;// 0 = Admin, 1 = institutional subscriber, 2 = individual subscriber
$_SESSION['auth'] = "OKAY";
So I need to pass a variable from one php to another php page but I dont know how to do it. I got this piece of code "$realname= $row['name'];" that stores the real name of the person to display it in another page after they successfully login, but when I try to use $realname variable in the other page it wont display it. How can I make this posible??? thanks in advance
page one login.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
include 'functions.php';
if(loggedin())
{
header("Location: userarea.php");
exit();
}
if(isset($_POST['login']))
{
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
//validate
if($username&&$password)
{
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($login) == 1)
{
while($row = mysql_fetch_assoc($login))
{
$db_password = $row['password'];
if($password == $db_password)
$loginok= TRUE;
else
$loginok = FALSE;
if($loginok==TRUE)
{
$realname= $row['name'];
if($rememberme == "on")
setcookie("username", $username, time() + 7200);
else if ($rememberme == "")
$_SESSION['username'] = $username;
header("Location: userarea.php");
exit();
}
else
die("Incorrect username or password. Please try again or contact your local admin.");
}
}die("Incorrect username or password. Please try again or contact your local admin.gdfgdfgdfg");
}
else
die("Please enter a username and password.");
}
?>
<h>Welcome!</h>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p / >
<input type="checkbox" name="rememberme"> Remember me<br />
<input type="submit" name="login" value="Log in">
</form>
</body>
</html>
Page 2 userarea.php (as you can see I declared $realname variable but I cant use it)
<html>
<body>
<?php
include 'functions.php';
if(!loggedin())
{
header("Location: login.php");
exit();
}
echo "Hello $realname";
?>
<h>Access Granted! Yeiy! </h>
Log out
</body>
</html>
This is exactly what sessions are for:
Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.
page one login.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
$_SESSION['realname'] = $row['name'];
Page 2 userarea.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
echo "Hello $_SESSION['realname']";
First pass $_SESSION['var_name']; on login page and then
start session_start() on the top of the userarea page and echo your session variable
echo $_SESSION['var_name'];
First of all I won't build a login system that uses a database, I know it's more secure but in this case it's not relevant...
I have three files login.php, admin.php and config.php. The users email and password is stored in variables in config.php. If the user is logging in a session should be set. Then if a user that hasn't logged in trying to access admin.php ":-(" should be printed. But now the ":-(" is always printed and something needs to be wrong with how I coded it all...
config.php:
<?php
//site data
$title = "Abbesplace";
$siteurl = "index.php";
//user data
$password = "testtest";
$email = "example#example.com";
$name = "Albin Larsson";
?>
login.php:
<?php
require_once("config.php");
if (($_POST['email'] == $email && $_POST['password'] == $password)) {
//login
session_start();
$_SESSION['logged']= "welcometomoon";
header("Location: admin.php");
} else {
echo "login faild";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
</head>
<body>
<div>
<form method="post" action="login.php">
Email:<input type="email" name="email"/>
Password:<input type="password" name="password"/>
<input type="submit"/>
</form>
</div>
</body>
</html>
admin.php:
<?php
if(isset($_SESSION['logged'])){
echo "Hello";
} else {
echo ":-(";
}
?>
Any suggestions on what I should make different?
(I'm a newbie when i comes to PHP)...
You have to call session_start on every page. Right now you are only calling it when you post to the login form.