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.
Related
usercheck.php
// Start a session.
session_start();
// Check the database for the user.
$user_check = $_SESSION['user_username'];
$ses_sql = mysqli_query($db,"SELECT user_username FROM users WHERE user_username='$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_user = $row['user_username'];
// If the check fails, redirect to the login page.
if(!isset($user_check)) {
header("Location: /index.php");
}
I have a file indcluded on every page that is supposed to check to see if the user is logged in. If they are, it shows the page. If not, it redirects back to the index.
The problem is that it's not redirecting and I cant quite figure out why. I can easily type the URL of the page I want to go to and bypass the login completely even with this file successfully included.
Am I doing something wrong or outdated?
Edit: Example of a page containing the file.
<?php
$pageTitle = 'Dashboard';
$pageClass = 'dashboard';
include_once('./assets/template/template.php');
// Start the page content.
function getPageContent() {
global $mysqli;
// Connect to database.
include_once('./assets/include/db-connect.php');
// Check the database for the user.
include_once('./assets/include/db-user-check.php');
?>
... some html ...
<?
// Close the database connection.
$db->close();
}
?>
Try changing if(!isset($user_check)) { to if(!isset($login_user)) {. It could be that the value of $_SESSION['user_username'] isn't correct. If that isn't the case, try var_dump($_SESSION); exit(); inside your if statement and troubleshoot from there.
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!!!!!!!
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.
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();
<?php
session_start();
include 'db.php';
include 'header.html';
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['email'])) {
header("location:profile.php");
} elseif(!empty($_POST['email']) && !empty($_POST['pass'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = md5(mysql_real_escape_string($_POST['pass']));
$sql = mysql_query("SELECT id, name, email, pass FROM users WHERE email='$email' AND pass='$pass'");
$row = mysql_fetch_array($sql);
$id = $row['id'];
$email1 = $row['email'];
$name = $row['name'];
$num = mysql_num_rows($sql);
if($num == 1) {
$_SESSION['id'] = $id;
$_SESSION['email'] = $email1;
$_SESSION['name'] = $name;
$_SESSION['LoggedIn'] = 1;
$update = mysql_query("UPDATE users SET lastlogin=NOW() WHERE email='$email1'");
header("location:profile.php");
} else {
echo "<h1>Error</h1>";
echo "<p>Sorry! Either your account could not be found or you have entered the wrong email or password. Please try again.</p>";
}
}
?>
This script works perfectly in my localhost environment but when uploaded to host, it does not go to the profile.php after logging in. Also, it doesn't redirect to profile.php if the session is set or not empty. Any ideas?
And second question, is my code correct for updating the 'lastlogin' to the current time? What does the database structure have to be for this? It is not updating in my database.
Thank you for your help.
your code is very ok for updating the lastlogin, but what is the error you get? please give what type of error you get on this. logically your code seems to be right, it may be some syntax error. add error_reporting(E_ALL) on top of your page and see what error is occurred actually.
header("location: profile.php");
^ //space should present because in some host environment it creates problem
If you are redirecting to the login script from a form using most likely POST, shouldn't you use $_POST[''] instead of $_SESSION?
Just a thought.
Always use exit(); after header redirection
Ok figured it out with an extensive search. The headers were already being sent with the
include header.html
line so it could not perform the
header(location: profile.php)
line. I had never heard of this issue before until now. So to resolve this issue, I just moved
<?php
...
include header.html
?>
to the bottom of the php code right before the HTML starts. Now the include header line can do it's thing and then the header will still be loaded for the page.
Thanks for all your help with this.