Sessions apply in more than one website - php

I have made 2 websites that use a log in system and everything works fine on both of them. The user can log in and log out of both. I am using xampp and have both websites open in Chrome in two tabs. On both websites I have the email address of the user displayed when the user logs in. The problem is when I log into website A al the switch to website B and refresh the page I am logged in on that website as well with the email address that I logged in with on website A. This address that is display also displays when there is no account associated with the apposite website. My question is how do restricted the session to the single website.
This is the login action
<?php
include 'db.inc';
session_start();
$UserEmail =$_POST["EmailAddress"];
$UserPassword =$_POST["Password"];
$query = "SELECT * FROM members WHERE EmailAddress = '$UserEmail'
AND password = '$UserPassword' ";
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
mysql_select_db($databaseName) or die ("Unable to select database!");
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
$_SESSION["authenticatedUser"] = $UserEmail;
// Relocate to the logged-in page
header("Location: Index.php");
}
else
{
$_SESSION["message"] = "Could not log in as $UserEmail " ;
header("Location: Login.php");
}
mysql_free_result($result);
mysql_close($connection);
?>
And this is when the user is logged in.
<?php
session_start();
if (!isset($_SESSION["authenticatedUser"]))
{
$_SESSION["message"] = "Please Login";
header("Location: Login.php");
}
else
{ ?>
This is where the user email address is displayed
<div class="Login">
<ul>
<?php if(isset($_SESSION['authenticatedUser']) && $_SESSION['authenticatedUser'] != null ) {?>
<li>Welcome <?php echo $_SESSION["authenticatedUser"] ?> </li>
<li><span>Log Out</span></li>
<?php } else {?>
<li><span>Log In</span></li>
<?php } ?>
Hope this is all relevant!

I would recommend you read this manual page:
http://de2.php.net/manual/en/session.examples.basic.php
and this wiki page:
http://en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Path
and the source of your problem should be clear.

A session is usually handled on the browser side by a cookie. A cookie has a domain: the site and path to which the cookie applies. Look at the cookies that are set in your browser; your site's session cookie likely has a domain that applies to both of your web sites.
You'll need to make sure that the path on each site's session cookie is specific enough that the other site won't pick it up.

Related

all the links redirects to index.php

I have a php script. Many of my customers are using it. But for few they say, they are able to login but when they click on any links from the menu, it just redirects to index.php
I have checked my code, menu links, folders... I have even checked users browser settings, antivirus, firewall... But no problem.
I am not getting why it is happening. here is my session file, while submitting login details i include this file
admin_auth.php
session_start();
if(isset($_SESSION['ADMIN']))
{
$_SESSION['name'] = $_SESSION['ADMIN'];
try {
$bdd = new PDO('mysql:host=localhost;dbname=nerp', 'root', '');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$m1 = "select * from users where username='".$_SESSION['ADMIN']."'";
$resultat = $bdd->query($m1) or die(print_r($bdd->errorInfo()));
//$m2 = mysql_query($m1) or die (mysql_error());
//$m3 = mysql_fetch_array($resultat);
$m3 = $resultat->fetch(PDO::FETCH_ASSOC);
$_SESSION['uid'] = $m3['id'];
$_SESSION['name'] = $m3['firstname'] ." ". $m3['lastname'];
$_SESSION['pos']= $m3['position'];
$_SESSION['department'] =$m3['department'];
$_SESSION['location'] =$m3['location'];
$_SESSION['password'] =$m3['password'];
$_SESSION['auth'] = md5( date('Ymd') . $_SESSION['password'] );
$_SESSION['email'] = $m3['email'];
}
else
if(!isset($_SESSION['ADMIN']) )
{
header("location:index.php");
}
login_submit.php
<?php
ob_start();
error_reporting(0);
session_start();
include("connect.php");
$user=$_POST['login_name'];
$pass=$_POST['login_password'];
$sql="SELECT * FROM users WHERE username='".$user."' AND password='".$pass."' ";
$query=mysqli_query($con, $sql) or die(mysqli_error());
$row=mysqli_fetch_array($query);
$username=$row['username'];
$count=mysqli_num_rows($query);
if($count==1)
{
$_SESSION['ADMIN']=$row['username'];
$_SESSION['name'] = $row['firstname'];
header("location:dashboard.php?user=".$_SESSION['ADMIN']."");
}
else
{
header("location:index.php");
echo "could not connect";
}
?>
is there any problem with this? . if not, why they are not able to open any links.
Based your code, and the symptom you described of those few users, it looks like those few users have disallowed cookies. So when a user with cookies disallowed goes to make a subsequent request after authenticating, they don't send the PHPSESSID cookie (here you can see an example)
So, what happens in your code is, the server sees isset($_SESSION['ADMIN']) is not set, and it drops them to the bottom of your code, which sends them back to index.php.
You can test this by disallowing cookies in your browser. A way to fix it (other than telling your users to enable cookies) is to attach some kind of ID to the URL and maintain an ID as your users move though the site. PHP can do this for you if you set:
<?php
ini_set("session.use_cookies",1);
ini_set("session.use_only_cookies",0);
ini_set("session.use_trans_sid",1);
session_start();
?>
Although I should mention this works with regular html links. It works by the PHP preprocessor adding its code to your links. Since you mentioned a menu, if your menu links are generated by javascript the PHP preprocessor won't know to add its code to the links there.

Allow content with $_Session

I've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!

PHP : Must login twice until session variables are set

SOLUTION: after many hours of searching, it seems this problem was occurring when I access my website without adding the "www." before the domain. so what actually was happening is, I was logging in with example.com/login.php sets session somewhere, that my member control doesn't recognize, so it redirects me back to www.example.com/login.php, that when I login everything works Ok.
when I login from www.example.com/login.php (with the www.) it logs in correctly from first attemp.
So I added a code to make sure I always have the www in the URL:
if ($_SERVER['HTTP_HOST'] == "example.com")
{
$url = "http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
and everything works well now. Hope it helps someone.
So, I have built over 3 websites, and all have same problem, I don't know why, I have to login twice till I'm rly logged in.. (till the session variables are set). Help is really appreciated, been trying to fix this and looking for solution since a long time...
session_start();
if ((isset($_SESSION['UserName']))&&(isset($_SESSION['LastActivity'])))
{
header ('Location: http://www.example.com/Account.php');
}
if (isset($_POST['username']))
{
mysql_connect("localhost","DBuser","pass") or
die ("could not connect to mysql");
mysql_select_db("DBNAME") or die ("no database");
$inputUserName = $_POST['username'];
$inputPass = $_POST['password'];
$datausername = mysql_real_escape_string($inputUserName);
$password=md5($inputPass);
$sqlCommand = "SELECT * FROM Members
WHERE UserName='$datausername' AND
Password='$password'";
$result = mysql_query($sqlCommand);
if (mysql_num_rows($result) > 0)
{
$_SESSION['UserName'] = $datausername;
$_SESSION['LastActivity']= time();
sleep(2);
$LoginDate = date('Y-m-d H:i:s');
mysql_connect("localhost","DBUPDATEusername","DBuserPass") or
die ("could not connect to mysql");
mysql_select_db("databaseName") or die ("no database");
mysql_query("Update Members SET LastLogin='$LoginDate' WHERE
UserName='$datausername'");
mysql_close();
echo '<meta http-equiv="Refresh" content="0;url=http://www.example.com/Account.php?p=Login_Success"/>';
}
else {
mysql_close();
echo '<div id="error_msg">Error: Information entered are not correct. Please check and try again.</div>';}
}
}
?>
<form...
login form (with action=""), and method post).
Note: I use the html refresh tag, because I can't use the header redirect.. (I get error that header is already sent).
and in the example.com/Account.php I do this check at the top of the code:
session_start();
if ((!isset($_SESSION['UserName']))||(!isset($_SESSION['LastActivity'])))
{
header('Location: http://www.example.com/?p=Must_Login');
}
And and it seems that first time I login and am redirected to account.php panel.. the session values are not set, and redirects me back to Must_Login page. I login again (same login page I use at first time. But the second time when I login, it does set the session values, and everything is OK.
Thank you very much for your help in advance!
SOLUTION: after many hours of searching, it seems this problem was occurring when I access my website without adding the "www." before the domain. so what actually was happening is, I was logging in with mydomain.com/login.php sets session somewhere, that my member control doesn't recognize, so it redirects me back to www.mydomain.com/login.php, that when I login everything works Ok.
when I login from www.mydomain.com/login.php (with the www.) it logs in correctly from first attemp.
So I added a code to make sure I always have the www in the URL:
if ($_SERVER['HTTP_HOST'] == "mydomain.com")
{
$url = "http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
and everything works well now. Hope it helps someone.
Connect to database before your Members select.
Start session if it has not been started yet.
Connect to the server and select the database before querying.
if (!isset($_SESSION)) {
session_start();
}
mysql_connect("localhost","DBusername","DBuserPass") or
die ("could not connect to mysql");
mysql_select_db("databaseName") or
die ("no database");
if ((isset($_SESSION['UserName']))&&(isset($_SESSION['LastActivity'])))
header ('Location: http://www.mysite.com/Account.php');
if (isset($_POST['username']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sqlCommand = sprintf( "SELECT * FROM Members
WHERE UserName = %s AND Password = %s", mysql_real_escape_string( $_POST['username'] ), md5( $_POST['password'] ) );
$result = mysql_query( $sqlCommand );
$rowsnr = mysql_num_rows( $result );
if (mysql_num_rows( $result ) > 0)
{
$_SESSION['UserName'] = mysql_real_escape_string( $_POST['username'] );
$_SESSION['LastActivity']= time();
sleep(2);
mysql_query(sprintf("UPDATE Members SET LastLogin = NOW() WHERE
UserName = %s", mysql_real_escape_string( $_POST['username'] )));
mysql_close();
echo '<meta http-equiv="Refresh" content="0;url=http://www.mysite.com/Account.php?p=Login_Success"/>';
}
else
{
mysql_close();
echo '<div id="error_msg">Error: Information entered are not correct. Please check and try again.</div>';
}
}
?>
Try putting following code AFTER you check for the login?
session_start();
if ((!isset($_SESSION['UserName']))||(!isset($_SESSION['LastActivity'])))
{
header('Location: http://www.mysite.com/?p=Must_Login');
}
PHP sessions are written to the session handler after the script which started the session finishes execution. In your case the first script started the session and updated session variables 'username' and 'lastactivity' then redirected to another page. But still the session values are in memory - not registered to be used in the second script.
One way to fix the problem is to call
session_write_close();
before (or after) sleep(2);
for more information see here
try session_set_cookie_params(0, '/', '.domain.com') before your session_start();
I had the exact same problem, in my case I was redirecting to the website address after login:
header('Location: http://mywebsite.com');
die();
Even manually closing the session before the redirect didn't help.
I fixed it by instead redirecting to a specific page:
header('Location: index.php');
die();

Password protect a page?(with db access)

Couple questions here: My end goal is to password protect the file logged_in.php.
Note: I'm only a beginner/intermediate programmer so i would like clear explanations, please.
First off, i have set a username and password within a database table.
I have two pages: login.php and logged_in.php(names are just for example purposes). How do i "require" a user to first go through login.php(the log in process) in order to gain access to logged_in.php(if the entered username/password are correct)?
Is this the best way to password protect a page?
What i've tried:
Login.php:
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
header("location:logged_in.php");
}
else
header("location:bad_login.html");
}
?>
The problem with my code at the moment is that, someone can directly type in the URL of logged_in.php and access the page without being "required" to go through login.php first(i'm sure this is obvious to everyone..).
I put require(login.php); at the top of logged_in.php; however, that didn't work out.
I've checked google for some good tutorials on this topic, unfortunately i couldn't find any that had clear explanations.
I also saw a few other questions regarding this topic on stackoverflow, but they didn't really help me out.
I'm also interested in being able to pass-protect my page using the method phpMyAdmin uses(when you type in the URL and press enter it drops down a menu from the top of the browser asking for a username/password). I don't know how that works. If someone can tell me how that works i'm willing to completely disregard the method i'm attempting to use at the moment(if the phpMyAdmin method is secure enough and is fairly easy to implement).
Thanks in advance!
Use $_SESSION variable:
<?php
session_start();
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $user;
header("location:logged_in.php");
exit();
}
else
header("location:bad_login.html");
exit();
}
?>
logged_in.php:
<?php
session_start();
// check if $_SESSION was setting before
if (!isset($_SESSION['username']))
{
header("Location: login.php?e=access_denied");
exit();
}
?>
The phpMyAdmin login is different because use the MySQL username and password to login, so phpMyAdmin does not need to create a database and table to login like your code
Also you need the logout:
logout.php
<?php
session_start(); // <-- Oops!!
// unset all $_SESSION variables
session_unset();
session_destroy();
header("Location: logged_in.php?m=logout_success");
exit;
?>

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