SESSION variable wont continue to next page - php

Even though I have searched and forums I am failing to get a Session Variable to continue to the next page.
Every page has session_start(). Each Header has exit() after it.
If I add a new member the SESSION Variable is fine. But when I log on the SESSION Variable gets lost after login.
Here is the code for the Login Page. Everything works except for the SESSION variable wont parse to the next page. What am I missing? oh and the code is a bit messy a bit like my workstation.
<?php
session_start();
//Connection to DB in the usual way with check to DB
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
//hacking protection in the usual way
$sql = "SELECT * FROM table WHERE `u_password` = '$mypassword' AND `user` = '$myusername' ";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$ls = "Online";
$datenow = date("Y-m-d H:i:s");
$id = $row['id'];
$usql = "UPDATE addnewmbr SET loggedstatus = '$ls', logindate = '$datenow' WHERE id = '$id'";
if (mysqli_query($mdb, $usql)) {
$_SESSION["user_id"] = $row['id']; //this variable is lost on next page
$_SESSION["user"] = $row['user']; //this variable is lost on next page
$_SESSION["gender"] = $row['gender']; //this variable is lost on next page
if ($_SESSION['gender'] == "man") {
header('Location: newpage.php');
exit(); // the redirection $_SESSION['gender'] works so the variable is set
} else {
header('Location: anotherpage.php');
exit();
}
} else {
header('Location: back to indexpage.html');
exit();
}
?>
anotherpage.php
<?php
session_start();
echo $_SESSION["user"];
?>
result on this page after Vardump on test page
array(0) { }

Apart from you being vulnerable for SQL injections (preventable by preparing your statements, binding your values and executing it)
Why do you set $_SESSION["user"] equal to $row['user'] and not to $myusername?
In this case, they are the same since you fetch the row where user = $myusername
Not sure if that solves anything.

It was an easy fix after all.... For all that get stuck with SESSION variables being lost!
on the header just be careful..... remove the www from the header
e.g.
SESSION problem
header('Location: http://www.website.php');
SESSION fix
header('Location: http://website.php');
That's all there is to it.

Related

How can I send user session from one page to another till destroyed in php and mysql

I have session page with these code
session_start();
if (!isset($_SESSION['id'])){
header('location:order.php');
}
$ses_id = $_SESSION['id'];
I included it into my login page (order.php)
<?php include('session.php'); ?>
Here is the login scripts and functions
$username = clean($_POST['username']);
$password = md5($_POST['password']);
$apollos=$username;
$query=Login($username,$password);
$count = mysql_num_rows($query);
$row = mysql_fetch_array($query);
$phone=$row['Contact_Number'];
DeleteActivation($username);
if ($count > 0) {
$_SESSION['id'] = $row['memberID'];
UserPin($username,$pin,$member);
$From='eFarms';
$Message='Your User Login Pin from St. Apollos eFarms is '.$pin;
die("<script>location.href = 'login_sms.php'</script>");
session_write_close();
} else {
session_write_close();
}
Here is my Pin Validation Page
<?php include('header.php'); ?>
pin = clean($_POST['pin']);
$query=CheckPin($username,$pin,$member);
$count = mysql_num_rows($query);
$row = mysql_fetch_array($query)
if ($count > 0) {
$_SESSION['id'] = $row['memberID'];
die("<script>location.href = 'user_home.php'</script>");
session_write_close();
} else {
session_write_close();
}
Someone should please examine these codes, correct and show me how to receive the session to the USer Home Page as Username.
First, as provided by others, ur using very bad and insecure method !
Try to use PDO which is much easier (when u understand how it work) and it's much more secure !
Second, ur coding is not so clean, I think that's why u can't find the problem urself !
And finally, I think ur missing :
session_start();
in some part of ur code !
Before session start you have to check the session is already started or not like below in each script or in common script file.
if (!isset($_SESSION)) {
session_start();
}
Edited:
the above condition is not needed as it is checking internally as descripe in the documentation - http://php.net/manual/en/function.session-start.php
session_start();

PHP Session ending automatically

I do a lot of work using PHP frameworks but I am now building a simple login system from scratch and I am stumped. I am using PDO for my database queries. I have a simple login form which points to the same page using $_SERVER['PHP_SELF']. Then I have this code...
<?php
//LOG IN
if($_POST['login_submit']){
$username = $_POST['username'];
$password = $_POST['password'];
//Query
$database->query("SELECT * FROM users WHERE username = :username AND password = :password");
$database->bind(':username',$username);
$database->bind(':password',$password);
$rows = $database->resultset();
$count = count($rows);
if($count > 0){
session_start();
//Assign session variables
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged_in'] = 1;
} else {
$login_msg[] = 'Sorry, that login does not work';
}
}
When I login, its fine. It starts the session. But as soon as I go to another page the session is broken. I suspect maybe cause the session_start() is in the if($_POST['login_submit']) condition. But I could sware Ive done it like this before. Any help would be awesome..thanks!
The first line of your code...
if($_POST['login_submit']){
Only, if you submit your login form, the session is started.
And, on all other pages, you have to call session_start() ...

cannot pass session variables

if(isset($_POST["username"])&& isset($_POST["password"])){
include('config.php'); //this one connects to the database
$username = $_POST["username"];
$password = md5($_POST["password"]);
$sql2=mysql_query("SELECT * FROM clinic_staff WHERE username='$username' AND password='$password'");
$count2 = mysql_num_rows($sql2);
if($count2 == 1){
while($row2 = mysql_fetch_array($sql2)){
$id = $row2["staff_ID"];
$position = $row2["position"];
}
$_SESSION["id"] = $id;
$_SESSION["name"] = $username;
$_SESSION["password"] = $password;
$_SESSION["pos"] = $position;
header("location:index.php");
exit();
}
The problem is I can't echo the username in index.php. I don't know if it is passed successfully. in index.php i used echo $_SESSION["name"];
put session_start(); at the beginning of your document with no white space above it.
You need to look at session_start to start a session. Examples are here
I don't see session_start();. You have to call that function at the top of every page you use session variables. (At least I have to do that on my server, somebody said to me you should actually be able to use Session variables without session_start();, but everything that needed a session variable stopped working after I removed the calls to session_start();)

Session not being saved after logging in

Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.

PHP MySQL login function

I'm using this:
function authUser($username, $password){
connectDB();
$sql = "SELECT id, username FROM users where username = '".$username."' and password = '".$password."'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0){
while ($row = mysql_fetch_array($result)){
$username = $row['username'];
session_start();
session_register('username');
return $username;
}
}
closeConn();
}
With a combination of this:
$auth = authUser($username, $password);
if (isset($username)){
header( "Location: index.php" );
}
And then on the index.php (where i redirect them if a successful login) i'm trying to echo $username. But nothing is showing? Any ideas? Is this function the problem?
EDIT:
have now changed it so:
if ($num_rows > 0){
while ($row = mysql_fetch_array($result)){
$_SESSION['username'] = $row['username'];
return true;
}
}
Is that right?
I would change:
while ($row = mysql_fetch_array($result)){
$_SESSION['username'] = $row['username'];
return true;
}
into:
$row = mysql_fetch_array($result);
$_SESSION['username'] = $row['username'];
because you want to login and get ONE person out
Please note that you are always re-directing to index.php, not only on a successful login;
$auth = authUser($username, $password);
if (isset($username)){
header( "Location: index.php" );
}
$username is set, both on a successful and a non-successful login.
You need to use session_start() on the index page as well.
Make sure index.php has a session_start() called at the top of the script, and also, try using $_SESSION['username'] instead of just $username. A lot of servers nowadays are set up so you have to call the full variable (with $_SESSION) rather than just the shortened version. Read about Register Globals at http://php.net/manual/en/security.globals.php. If you still have problems, take the session_start() out of the authUser function and move it to the first line of that script as well.
Variables are not global between page instances, you need to put the variable in $_SESSION if you want it to be accessible over multiple pages.
First, session_register is deprecated. use $_SESSION:
$_SESSION['username'] = $row['username'];
Second, your authUser() function returns either a username (if successful) or nothing. Then this code:
$auth = authUser($username, $password);
if (isset($username))...
should be changed to
$username = authUser($username, $password);
if (isset($username))...
And one more thing, checking for passwords in the clear is a very very bad thing :) Consider hashing it with MD5().
Good luck!
If you use mysql_fetch_array then you should use array, like this: $row[0]
You can use mysql_fetch_assoc() to use table column name ($row['username'])

Categories