I'm trying to make a login and logout script for a page but for some reason its not working very well for me. it seems to work fine until I try to logout. it seems to destroy the session variables, but it still lets me view the page.
heres my login code:
Code:
login.php
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
////// Logout Section. Delete all session variable.
session_destroy();
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match.
{
session_register("uname"); // Craete session username.
header("location:loged.php"); // Re-direct to loged.php
exit;
}else{ // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
// End Login authorize check.
?>
logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['uname']);
// Delete all session variables
session_destroy();
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
}
?>
thanks to every one...
You are setting the session, but you are not checking it any where that whether it is set or not. means you are not checking that user is logged in or not.. you need to do like this
if (!isset($_SESSION['uname'])) /*If uname not set then it is a guest*/
{
//page contents for guest user
}
else
{
//page for authenticated user.
}
session_register() is deprecated as of PHP 5.3.0. Replace:
session_register("uname"); // Craete session username.
with:
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
Log out with (replacing session_destroy()):
////// Logout Section.
unset($_SESSION['uname']);
The final result will look like:
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
// Logout Section
if (isset($_SESSION['uname']))
unset($_SESSION['uname']);
// Login Section
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match. {
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
header("Location: loged.php"); // Re-direct to loged.php
exit;
} else { // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
?>
Logout script (syntax error fixed and session_destroy(); since unnecessary):
<?php
// Inialize session
session_start();
// Delete certain session
if (isset($_SESSION['uname'])) {
unset($_SESSION['uname']);
}
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
?>
How to check if logged in:
session_start();
if (isset($_SESSION['uname']))
{
// logged in
}
else
{
// not logged in
}
In your page that you want to be accessed only by logged in user, do you check the value of $_SESSION['uname'] ?
I think only session_destroy(); function is good enough to log you out. You need not to unset the 'uname'. And for those pages that will come after user logged in then you must apply some session check functionality at the top of each page...
if uname is the value you use to validate if the user is logged you should try to put first:
session_destroy(); and then the unset($_SESSION['uname'])
I hope this works for you....
Related
I am creating a login for a website. I can get the code below working: It lets me log in! Yet I can't get a start session to work: People can still get to my pages via URL.
Log in PHP:
<?php
//calling connection to database
include "connection.php";
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
Start session code which says undefined variables:
<?php
include"includes/loginrequiredb.php";
if($_SESSION['username'] !=$user){
session_destroy();
header("Location: view.php");
die();
}else
{
echo "welcome to the site you have logged in" . $_SESSION['username'];
}
?>
Without starting the session you can not get the values from $_SESSION.
You just need to start session in your both files as:
session_start();
Note that you need to start_session() in both files only in just welcome file.
Side note:
I suggest to also use isset() for checking either value set or not.
Start the session with session_start and Add a session verification file in adminmain.php page.
<?php
//calling connection to database
include "connection.php";
#session_start();
//session
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
##### file verify.php #####
<?php #session_start();
if (#$_SESSION['username']!=$user) {
header ("location: index.php");
exit;
}
?>
I'm trying to create a user login system for use on a website I'm building. I have the login script and register script, but I'm having trouble with the logout and destroying the sessions.
Here's my index code. It gets the database info in config (doesn't do anything with it yet), then runs check-login to make sure the user is actually logged in. It has a logout button that routes to logout.php
<?php
include_once("config.php");
include_once("check-login.php");
session_start();
$username = $_SESSION["username"];
?>
<html>
<body>
<h1>
Hello <? echo $username ?>! We're still building, but feel free to... wait?
</h1>
<form action="logout.php">
<input class="logoutbutton" type="submit" value="Logout" />
</form>
</body>
</html>
Here is my check-login.php file. Notice that anytime I link back to the index, I'm using a $_GET to post some information into the address bar. There is no place where I simply go back to index.php
<?php
ob_start();
include_once("../myreadingplanner_config/config.php");
if(($_SESSION['username']) != null){ //If user is already logged in...
$username=$_SESSION['username'];
header("Location: index.php?Message=AlreadyLoggedIn$username");
}
else {
if(isset($_POST['username']) && strlen($_POST['username'])!=0){ //if username is valid
$username = $_POST['username'];
} else {
header('Location: login.php');
}
if(isset($_POST['password']) && strlen($_POST['password'])!=0){
$password = $_POST['password'];
} else {
header('Location: login.php');
}
$SQLString = "SELECT TOP(1) * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = sqlsrv_query($conn, $SQLString) or die ("");
if($result != null)
{
$_SESSION['username'] = $username;
header("Location: index.php?Message=YouLoggedIn$username");
} else {
header("Location: index.php?Message=UserLoginNotFound&Username=$username");
}
}
ob_flush();
?>
And finally here is my logout.php, which should (in theory) destroy the session, and head back to index.php. When it gets back to index.php, index.php will reroute to login.php using the include_once("check-login.php");
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
Just looking at my logic, there SHOULD be an infinite loop in the check-login, right? Because if the user is logged in, it should reroute to index, which includes check-login, which reroutes to index, which... etc.
If you want to check out the site for yourself, please go to www.myreadingplanner.com, and use this info to login (user will be deleted eventually)
Username: StackUser
Password: password1
So functionality wise, login.php should NEVER be visible unless you have a valid session, and when it does, it should say 'Welcome $username!'. But if you hit the logout button on index, it will still keep the session open, but it will be null.
Any advice on either why logout doesn't seem to fully logout the user OR why it is logging the user out but is keeping the NULL $_SESSION around?
To remove sessions use
unset($_SESSION['SESSION_VAR'] );
session_destroy(); //closes the session and prevents session riding
For more information I'd research session riding as you should close your session as soon as you can to prevent this.
Also do not unset the entire session global array.
//don't do this
unset($_SESSION);
First, have a look at index.php file. in that file, change the code below:
include_once("config.php");
include_once("check-login.php");
session_start(); // move the session_start function and place at the top of the script
$username = $_SESSION["username"];
change it, so that it becomes like this:
session_start();
include_once("config.php");
include_once("check-login.php");
$username = $_SESSION["username"];
This problem occurs because at the file check-login.php you do not declare the function session_start();
I have tested this problem. And it works!
I am trying to code a simple script,
I created a " ADMIN Panel " , so if the user is admin (admin=1) then he can pass and see the link/file
If he is not (admin=0) then he should be redirected to login page , and if is not Session['username'] he should go back to login page ,
but it seems that i have a problem with this code, in user panel it works , but in admin panel it doesn't
<?php
include './includes/db.php';
session_start();
// ADMIN CHECk
$username = mysql_real_escape_string($_SESSION['username']);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND admin=1");
$count = mysql_num_rows($result);
if($count != 1) // make sure user is a admin
{
session_start();
session_destroy();
header("location: login.php");
die;
}
if(isset($_GET['act']))
{
if($_GET['act'] == "logout")
{
session_start();
session_destroy();
header("location: login.php");
}
}
?>
Ok, first thing i see is that you don't declare the session first. Secondly, the mysql function is deprecated, mysqli will do what you need done. This fix should work for you. Also it would be easier to have a logout.php.
db.php
<?php
$db = new mysqli(host, user, pass, database);
?>
Then, in your page, you can run the queries like so:
<?php
session_start();
include './includes/db.php';
//check that the session exists
if(!isset($_SESSION['username'])
{
//the session does not exist, redirect
header("location: login.php");
}
// ADMIN CHECk
$username = $db->real_escape_string($_SESSION['username']);
$result = $db->query("SELECT * FROM users WHERE username='$username' AND admin='1'");
$count = $result->num_rows;
if($count != 1) // make sure user is a admin
{
header("location: login.php");
}
?>
Then in logout.php, you should remember to actually unset the session variables
<?php
session_start();
//unset session variables
unset($_SESSION['username']);
session_destroy();
header("location: login.php");
?>
I'm not very good at PHP and I have a little problem. I've been playing around with this script.
And I can't for the life of me figure out how to echo the username of a logged in user.
I tried to print all the information of the session like this:
var_dump($_SESSION)
but I just got the hashed password and the userlevel int.
Can someone maybe help me here? I just want to be able to echo the username.
You have to store the username in the session for it to be available on another page load, currently the script only stores these values in the session;
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['userlevel'] = $row[$this->user_level];
What you have to do is add the $username to the session that is passed into the login function, like below;
$_SESSION['username'] = $username;
The username will now be stored in the session with the key username.
To be able to use it on another page, make sure that before attempting to use it you initiate the session by calling the function session_start().
Basically, just write it inside like
session_start();
echo $_SESSION['username'];
or
echo $_SESSION['password'];
A brief explanation of how sessions work.
first you start the session and assign any value to a session ex:
session_start();
$_SESSION['username'] = 'john';
then echoing works like:
echo $_SESSION['username']; // will echo out 'jonh'
note session_start() must be shared in-between the pages you want to use the session
You have session_start(); on top ?
In the login function you should write the username to the session after a successful login.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
$_SESSION['username'] = $_REQUEST['username'];
}else{
//do something on FAILED login
}
}
<?php
include('db.php');
session_start();
$name=$_POST['name'];
$password=$_POST['password'];
echo $sql="SELECT * FROM register WHERE (name='$name' OR email='$name') AND password='$password'";
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0)
{
$_SESSION['user']=mysqli_fetch_assoc($result);
$row = $_SESSION['user'];
$role = $row['role'];
if($role == 1)
{
header('location:usermanagement.php');
}
else{
header('location:user.php');
}
}
else
{
echo "Wrong Username or Password";
header('location:login.php');
}
$conn->close();
?>
I have tried a session.php script which runs at the head of each page in my website to verify that the user has logged in before they can browse the site. However, now the process_login script won't load the secure landing page and it just reloads to the login page. I believe that my secure session is not being set correctly. Can someone further explain how this works to me?
This is the script, process_login, which executed when a user clicks login:
<?php
// Initialize session
session_start();
// Require database connection settings
require('config.inc');
// Retrieve email and password from database
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string(md5($_POST['password']));
$query = "SELECT * FROM $table WHERE email='$email' AND password='$password' LIMIT 1";
$result = mysql_query($query);
// Check email and password match
if(mysql_num_rows($result)) {
// Set email session variable
$_SESSION['email'] = $_POST['email'];
// Jump to secured page
header('Location: home.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
and this is the session.php script which is in the head of each page that requires a user to be logged in:
<?php
if (isset($_SESSION['email']) == 0) {
// Redirect to login page
header('Location: index.php');
}
?>
You need to include the code
session_start();
in the your file session.php to access your session variables
Or you should make sure that session auto start is enabled on your php configuration.