PHP Session value changing from page to page - php

I made a custom login script, and it works just fine. However, after it redirects to the homepage, the $_SESSION['username'] value is changed to 'root', no matter what value it had before hand. which 'root' is the username for my database login.
I have to type all of this in by hand, so it might have an obvious error or two-
main_login.php (php include_once on sidebar.php which is included on every page)
<?php
if(!isset ($_SESSION["username"])){
?>
<!-- Simple login form action="checklogin.php" method="post"-->
<?php
}else{
?>
<!-- Table to display welcome user, and logout link -->
checklogin.php:
session_start();
$db_name = "database";
$tbl_name = "users";
mysql_connect("localhost","root","password") or die("Cannot connect to SQL server");
mysql_select_db("$db_name")or die("Cannot select database.");
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$password = md5($password);
$sql = "SELECT * FROM $tbl_name WHERE username = '$username' and password = '$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}
else{
echo "<script type='text/javascript'>\n";
echo "setTimeout('redirect();',2000);\n";
echo "function redirect(){\n";
echo "window.location = 'index.php';\n";
echo "}\n";
echo "</script>\n";
echo "Wrong Username or Password";
login_success.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:index.php");
}else{
session_regenerate_id();
}
// Apply permissions - problem existed before all of this code
mysql_connect("localhost","root","password") or die("Cannot connect to database.");
mysql_select_db("database") or die("Cannot select database.");
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_num_rows($result);
mysql_close();
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
?>
<html>
<head>
<script type="text/javascripnt">
setTimeout("redirect();",4000);
function redirect(){
window.location = "index.php";
}
</script>
</head>
<body>
Login Successful.
<?php echo "Welcome ".$_SESSION["username"].".";
var_dump($_SESSION); // var_dump reveals that $_SESSION['username'] is still the login name.
?>
</body>
</html>
Once it goes through that whole process, everything is good. However, when it redirects to index.php, $_SESSION['username'] is now 'root'.
I'm asking to see if anyone has any idea why that might be happening (So I can understand the problem and prevent it in the future), and a fix to implement.
Thanks everyone.

The answer is very simple:
There is some code in your application which changes $_SESSION['username'] value to 'root'.
you have to investigate your code and find that place. Not a big deal

this part seems weird:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_num_rows($result);
mysql_close();
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
try this:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($result);
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
msql_close();

Why are you setting the $_SESSION['username'] variable again on login_success.php You're setting the variables on check_login.php, correct?
Here is what I would do
On login_success.php print out your session variables to see whats going on. I can almost gaurantee something is happening with your sql query. Set a condition to make sure you're actually getting results.
print_r($_SESSION);
if(!$_SESSION['username']) die('no session user name');
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($result);
if(mysql_num_rows($result) == 1){
$_SESSION['username'] = mysql_result($result,0,'username'); //why do you need this?
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
mysql_close();
}
else die('no user found');
Also on your checklogin page change the if statement to look for an actual variable in $_SESSION['username'] not just if it is set, I try to stay away from isset().
For the love of god don't store plain text passwords, it doesn't cost anything to implement a secure password hashing scheme. Its super easy to leverage php's crypt() function, also check this out for an open source secure method. http://www.openwall.com/phpass/

Well,
Your comment sense is probably right, you are setting it to root without realizing it. I just realized, after 2 hours of troubleshooting, that's what I was doing!
No matter what I tried, $_SESSION['username'] was changing from a real username to 'root'.
I finally realized that $_SESSION['username'] was NOT actually changing anywhere, but $username was. Here is why:
<?php
if(!empty($_SESSION['username'])){
$username = $_SESSION['username'];
require_once '../includes/connect_to_db.php';
echo $_SESSION['username']. ' is correct but '. $username. 'is not.';
}
?>
Finally we see in the required file connect_to_db.php:
<?php
$host="localhost"; // Host name
$username="root"; // mysql username
$password=""; // mysql password
$db_name="BH_web_DB"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect: ". mysql_error());
mysql_select_db("$db_name")or die("cannot select DB");
?>
Simple fix:
$db_username="root"; // mysql username
So I was in fact setting it too root =) hope this helps another.

I was having the same issue, turns out I didn't session start on the page where it displays 'root'.
if (!session_id()) session_start();
This helped!

Related

PHP login got Too Many Redirect Loop error

Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.

access page only if logged in with php

I'm new to PHP, and I want to make possible to access a page only if a person is logged in.
login2.php:
<?php
$host="hostxyz";
$dbusername="userxyz";
$dbpassword="xyz";
$db_name="dbxyz";
$tbl_name="tblxyz";
mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$username=$_POST['username'];
$password=$_POST['pwd'];
$encryptedpwd=sha1($password);
$username = stripslashes($username);
$encryptedpwd = stripslashes($encryptedpwd);
$username = mysql_real_escape_string($username);
$encryptedpwd = mysql_real_escape_string($encryptedpwd);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and pwd='$encryptedpwd'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
$_SESSION['username'] = $username;
$_SESSION['pwd'] = $encryptedpwd;
header("location:login_success.php");
}
else {
echo "Username e/o password errata.";
}
?>
login_success.php:
<?php
session_start();
if($_SESSION['username']){
header("location:area_utenti.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
area_utenti.php (member_area.php translated):
<?php
session_start();
if(!isset($_SESSION['username'])) {
header("location:dologin.html");
}
?>
<html>
<head>
<title>Area Utenti</title>
</head>
<body>
<p>Sei loggato, bravoh!</p>
</body>
</html>
dologin.html is simply a page where unregistered/unlogged users are redirected if they try to access to member area.
The problem is that after I log in, I should be redirected to area_utenti.php, but area_utenti.php redirects me to dologin.html. What did I do wrong?
Sorry for bad English.
P.S.: I tried to search for solutions on StackOverflow, and I tried to apply them, but they didn't work.
You forgot to start the session in one of your scripts, maybe thats the issue, might worth checking it:
<?php
session_start();
$host="hostxyz";
$dbusername="userxyz";
$dbpassword="xyz";
$db_name="dbxyz";
$tbl_name="tblxyz";
//...rest of your code...

Php Login works but ignoring user type field in MySQL script

Was hoping I could get a bit of a hand on this login that I have been stuck with for past few days.
Basically what it is is that the login will log in the user, but will go to the same page every time. What I want it to do is: If the user is an admin, take that person to the admin page. If user, to the userpage.
I've set it up in the database were there is a usertype field and have hard coded 2 users, with one have admin as their usertype and the other as user.
<?php
session_start();
$host="xxxxxxxxxxxxx"; // Host name
$username="xxxxxxx"; // Mysql username
$password="xxxxxxx"; // Mysql password
$db_name="xxxxxxxx"; // Database name
$tbl_name="member"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
$num_results = mysql_num_rows($result);
$array = mysql_fetch_array($result);
$_SESSION['username']=$array['username'];
$_SESSION['password']=$array['password'];
$_SESSION['usertype']=$array['usertype'];
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
$_SESSION['username']=$_POST['username'];
$_SESSION['password']=$_POST['password'];
if ($array['usertype']=="user")
{ header ("location: userpage.php"); }
else if ($array['usertype']=="admin");
{ header ("location: adminpage.php"); }
} else {
echo "Wrong user or password";
}
?>
The above is the latest code I have used. Each time I log in it seems to skip the 1st header, and go straight to the second one. I've even printed out the session after I have logged in and it does take the usertype from the table.
Don't have any more clues on how to fix this.
Not sure if its what's causing your problem, but you have a stray semicolon on the end of here here that needs removing:
else if ($array['usertype']=="admin");
I can see 2 errors
use uses double } after the header ("location: adminpage.php");
Semicolon ; after else if ($array['usertype']=="admin")
Solution
if ($count == 1) {
$_SESSION ['username'] = $_POST ['username'];
$_SESSION ['password'] = $_POST ['password'];
if ($array ['usertype'] == "user") {
header ( "location: userpage.php" );
} else if ($array ['usertype'] == "admin") {
header ( "location: adminpage.php" );
} else {
echo "Wrong user or password";
}
}

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;
?>

mysql_real_escape_string causes problems?

Okay. So I made a form. If I put in mysql_real_escape_string on my variable $usrname (yes its spelled right) that was retrieved from the form, it returns my other variable, $verify as false. Take a look:
<html>
<body>
<?php
session_start();
include("mainmenu.php");
$usrname = $_POST['usrname'];
$password = sha1($_POST['password']);
$con = mysql_connect("localhost", "root", "Y0U_C#NT_H#NDLE_THE_TRUTH!");
if(!$con){
die("Unable to establish connection with host. We apologize for any inconvienience.");
}
mysql_select_db("users", $con) or die("Can't connect to database.");
$select = "SELECT * FROM `data` WHERE usrname = '$usrname' and
password = '$password'";
$query = mysql_query($select);
$verify = mysql_num_rows($query);
if($verify==1){
$_SESSION["valid_user"] = $usrname;
header("location:index.php");
}
else{
echo "Wrong username or password. Please check that CAPS LOCK is off.";
echo "<br/>";
echo "Back to login";
}
mysql_close($con);
?>
</body>
If I put the mysql_real_escape_string in either my registration form or login form, it returns $verify as false. What's wrong?
Please make sure "Magic Quotes" is off in the PHP settings. How to disable it is explained here.

Categories