PHP unset and desroyed session starts itself - php

I got a little problem with my php code here... Can you please help me out?
The problem is that when i, in my logout.php, unsets and destroys sessions, it works the first time i load some of my other pages.. but when i refresh right after, the session is started again, which i dont really understand? Because i have my page to look for a session with a specific name. Here is my code:
Login.php:
<?php session_start();
//Get username and password
$email = $_POST['email'];
$password = $_POST['password'];
//Sorting special characters away, with exception of "-" and "."
stripslashes($email);
$email = preg_replace('/[^A-Za-z0-9#\.\-]/','', $email);
//Getting the password from the database
$link = mysqli_connect("****", "****", "****", "****");
if (mysqli_connect_errno($connect))
{
echo "Connection Failed!";
mysqli_close($connect);
}
$sql = "SELECT * FROM admins WHERE email = '". $email . "'";
if ($result = mysqli_query($link, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$db_password = $row[2];
}
mysqli_free_result($result);
}
mysqli_close($connect);
//Compare DB-password to entered password
if ($db_password == $password)
{
$_SESSION['admin'] = $email;
header("Location: ../index.php");
exit();
}
header("Location: index.php");
exit();
?>
Logout.php:
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Index.php:
if (isset($_SESSION['admin']))
{
echo '<div id="admin"><br>
<h3>'.$_SESSION["admin"].'</h3>
<span>Admin panel</span><br>
<span>Log out</span>
</div>';
}
And yes, i got session_start() on top of every one of my pages.
As you can see in the index.php, i want some code to be written if $_SESSION['admin'] is set. And when i destroy the session in my logout.php, and goes to index.php, it works the first time i load the page. But i i refresh, the code reappear, which means the session must have been set again, somehow! But i dont know why? Please help!
EDIT: I have put the whole code of the login.php now. The rest of the other 2 pages, is pure HTML. What i have posted is all my PHP code!

It might because of the PHPSESSID cookie. just try it by removing PHPSESSID cookie from browser
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
setcookie('phpsessid','value',time()-1);
echo '<h1>You have been succesfully logged out!</h>';
exit();
}

Once you refresh, your following condition staisfies:
if ($db_password == $password)
connection establishes, session is created and you are redirected to index.php from login.php.
Change this condtion and your script works

Related

I need help on PHP session on login

Please help, I am writing a php login script. I really need help. I have tried it for days without success.
I have this line of code on top of my login page
<?php
ob_start();
if (isset($_SESSION['admin'])) {
header('Location: admin.php');
}
Here is my login (index.php) script
<?php
require "includes/dc_conect.php";
if (isset($_POST['submit']))
{
$username=mysql_real_escape_string(htmlentities($_POST['username']));
$password=mysql_real_escape_string(htmlentities($_POST['password']));
if($username==NULL || $password==NULL)
{
echo 'All fields must be field';
}
else
{
$sql="SELECT * FROM users WHERE username='$username' && password='$password'";
$result=mysql_query($sql, $link);
$dbfield=mysql_fetch_assoc($result);
$count=mysql_num_rows($result);
if($count>0)
{
//Set username session variable
$_SESSION['admin'] = $username;
header('Location: admin.php');
}
else
{
echo"<blink>"."<font color='#FF0000'>"."Username and/or Password is incorrect!"."</blink>";
}
}
}
?>
when I am logging in, it returns back to the login page
here is the script on the top of my admin.php
<?php
// start session
ob_start();
session_start();
//check to see if user is already loged in den redirect
if(!isset($_SESSION['admin']))
{
header("Location: index.php");
exit();
}
else
{
require "includes/dc_conect.php";
$username=$_SESSION['admin'];
$sql="SELECT * FROM users WHERE username='$username'";
$result=mysql_query($sql, $link) or die (mysql_error());
$dbfield=mysql_fetch_assoc($result);
$count=mysql_num_rows($result);
echo $dbfield['username'];
}
?>
Please could someone help me?
You need to call start_session() before you try to read from $_SESSION
<?php
ob_start();
session_start();
if (isset($_SESSION['admin'])) {
header('Location: admin.php');
As MarcB points out, you also need to do this before setting the session variable in index.php.

Losing session values after header redirection

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

unable to use login session across pages in php

I am unable to pass login session information to other HTML pages. Below is my login php code. I can successfully login but cant pass on the information to other pages like HTML home page and it gets opened though I am not logged in to same. I tried different codes for the same
<?php
require_once("config.php");
$email=$_POST['email'];
$password=$_POST['password'];
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string(strip_tags($email));
$password = mysql_real_escape_string(strip_tags($password));
// Check occurence of email password combination
$sql="SELECT * FROM register WHERE email='$email'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $email, table row must be 1 row
if($count==1)
{
$row = mysql_fetch_array($result);
if($password == $row['password'])
{
session_start();
$_SESSION['login'] = "1";
header("location:home.html");
exit;
}
else
{
echo "Please enter correct Password";
header("location:login.html");
session_start();
$_SESSION['login'] = ''
exit();
}
}
else
{
header("Location:register.html");
exit();
}
?>
Below is the php snippet that I use at the top of my HTML page:
<?php
require_once("config.php");
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.html");
exit;
}
?>
change the .html file to a .php file. And there start with session_start();, this because HTML pages are static and PHP are dynamic.
After this you will be able to use $_SESSION['login']
session_start(); should be used only onse, when login is successful.
delete that line from your "php snippet that I use at the top of my HTML page" and everything should be ok.
So your code would be:
<?php
require_once("config.php");
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.html");
exit;
}
?>

Session information being lost

I'm running a login script and according to who logs in I redirect to one of two pages
If I direct to a page that is in a directory below the main directory all works fine, however if i direct to a page that is above the directory in which the index.php file sits, the session information seems to be lost and the user is asked to login again
I know that I could simply place the second page in a directory below the main directory but I would like to understand if it is possible to maintain the session information when directing to a page above the main directory
the user goes to a page called login.html, when they have input there information, they are sent to login.php, it is here where the redirect occurs
if ($username==$dbusername&&$password==$dbpassoword)
{
if($admin == "1"){
header('location: http://www.edit.domain_name.co.uk/');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}else{
header('location: /member');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}
}
I have put session_start (); at the beginning of every page where the user would need to login to access. Any input would be greatly received
the full code for the login script is
<?php
session_start () ;
$username = $_POST['username'] ;
$password = $_POST['password'] ;
################# ADMIN OR NOT ###################################################
include_once "mysql/global.php";
$result = mysql_query("SELECT admin FROM users WHERE username = '$username'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$admin = $row[0];
################# ###############################################################
if ($username&&$password)
{
include "mysql/global.php";
$query = mysql_query("SELECT * FROM users WHERE username='$username'") ;
$numrows = mysql_num_rows($query) ;
if ($numrows!=0)
{
while ($row = mysql_fetch_assoc($query) )
{
$dbusername = $row['username'] ;
$dbpassoword = $row["password"] ;
}
// check to see if they match!
if ($username==$dbusername&&$password==$dbpassoword)
{
if($admin == "1"){
session_start();
header('location: http://www.edit.domin_name.co.uk/admin');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}else{
session_start();
header('location: /member');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}
}
else
echo "<center>incorrect password!</center>" ;
}
else
die ("<center>That user does not exist!</center>") ;
}
else
echo ("<center>Please enter a username and password</center><br/>") ;
die ("<a href=\"index.php\"><center><b>Click here to try again</b></center></font>");
?>
In order to load sessions, you must place session_start() at the top of each page.
Also, you need to call session_start() before setting them and before redirecting:
if ($username == $dbusername && $password == $dbpassoword) {
if($admin == "1"){
session_start();
$_SESSION['username']=$username;
$_SESSION['id']=$id;
header('Location: http://www.edit.domain_name.co.uk/');
}
else {
session_start();
$_SESSION['username']=$username;
$_SESSION['id']=$id;
header('Location: /member');
}
}
header('location: /member');
For a start, this is invalid. The Location header should be followed by a full, not a relative, URL.
Secondally, if /member is a directory, and you access www.example.com/member, Apache is quite likely to redirect you to example.com/member/, adding the forward slash and dropping the www.. The move to a different domain name is likely to result in the loss of session data.

How to prevent browser from going back to login form page once user is logged in?

I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.

Categories