I will explain my problem
From index.php I POST my login and in login.php I store session details (like name) e.g.:
$_SESSION['name'] = mysql_result($res,0,"name");
then I am forwarded back to index.php.
Here I want to show logged-in-user's name:
echo $_SESSION['name']
and also all names from the DB:
$result=mysql_query($query);
for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
$name =$row['name'];
echo $name;
}
And here comes the problem: after I log in, everything (both user's name and all names) is displayed correctly. But when I refresh the page echo $_SESSION['name'] shows the last name in the databse == $name instead of the one that was
So I guess I need to clone mysql_result($res,0,"name"); when storing into $_SESSION['name']
Thank you very much
EDIT
the only thing i store in session is the login name. And when the person is logged-in he can see all people from database.
If you are looking to clone an object then you can try the following
$object2 = clone $object1;
From the php documentation it seems that some objects do not support cloning, so if this is the case then you could try the following (again, from comment in php documentation) to do a deep copy
protected function deepCopy($inputObject) {
return unserialize(serialize($inputObject));
}
There are some other good points made in the comments of the documentation page which can be found here http://php.net/manual/en/language.oop5.cloning.php
Best regards
In my opinion you are better off not storing all the other names in the session. Being a database app with logins I assume other people can use and update the data, meaning that any time they change something, your session-saved data will be obsolete on refresh.
Try just letting them login and set their on credentials, then when they get back to index check that they are logged in and fetch the names at that point. That way you don't have to worry about cloning the fetch AND you have the most up to date info.
Related
i'm trying to a build a secure sessionID.
Usually i store the UserID as the $_SESSION['session'];, now im not too sure if it is really secure to have the userID as the sessionID. so what i have done is tested this theory although now i cannot access the users information and after i kill the session the sessions are still active and available?
CODE to check login if true or false:
if(password_verify($userPass, $user['userPasswd']))
{
session_start();
$UID = str_replace($user['text'].$user['text1'], '', $user['uniqID']);
$_SESSION['SESSION'] = sha1(md5(sha1($UID)));
return true;
} else {
return false;
}
Logout Script: EDIT fixed using $_SESSION = array();
public function userLogout()
{
session_destroy();
unset($_SESSION['SESSION']);
return true;
}
Script to access users table information (username, email etc):
$userID = $_SESSION['SESSION'];
$stmt = $userClass->runQuery("SELECT * FROM users WHERE uniqID=:userID");
$stmt->execute(array(":userID"=>$userID));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($_SESSION['SESSION']); //Prints out session even if not logged in
print $user['Username']; //Prints out nothing
i'm not sure if i missed a step or if hashing a session is even necessary, maybe i am doing something incorrectly. Essentially i am trying to secure the userID via a hash instead of having it displaying the users actual ID. Using the hash i would like to match and gain access to the users column.
ADDITIONAL NOTE: if i change the session to get the actual userID eg: 1
$userID = 1; //i did set the $_SESSION var to the userID to check if logout works
$stmt = $userClass->runQuery("SELECT * FROM users WHERE userID=:userID");
$stmt->execute(array(":userID"=>$userID));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($_SESSION['SESSION']); //prints out 1 //still does not destroy session after userLogout() is initiated
print $user['Username']; //Prints username which is correct
been boggled by this for hours, maybe a different set of eyes and experience might help x_x.
(this is a comment, but its a bit long)
As ADyson says, this is very confused coding. Neither your code nor your narrative explain what you are trying to achieve here. What is the threat model? What is your definition of "secure"? $_SESSION['SESSION'] is not the session id.
If you store a static map between the (effectively random, but not random enough) identifier stored in the session and the username, then all you've done is limit the performance and scalability of the system - I cannot see how it adds any value for security.
There is a usage model where you might want a warrant-proof user database, where you would hash usernames - but this is not it.
There are models for protecting the session data from other subscribers on a shared host (with poor partitioning). This is not that either.
There are models for ensuring that session data is protected in backups....and, nope, this isn't very good for that either.
sha1(md5(sha1($UID)));
This is silly.
Take some time to understand how the default session handler actually works before you start trying to improve it by throwing code at it (hint: there are things in there which are not suitable for every application, but if you want to improve them, use a custom handler - not wrapping the default handler in additional code). But before you write any code, you need to get your head around exactly what you are trying to achieve.
You need to follow such way:
session_start();
// Unset all of the session variables.
$_SESSION = array();
// Finally, destroy the session.
session_destroy();
I have this in my $_SESSION setting script:
<?php
//----------------------// Start session----------------------
if(!isset($_SESSION))
{
session_start();
}
//------------------------------------------------------------
//------------------// Check if Username $_SESSION is set------------------------------------------
if (!$_SESSION['Username']) { // If not current User
header("Location: ./logout.php"); // Session destroy file that leads to session logout landing page
exit();
}
//------------------------------------------------------------
?>
Now, what I basically do is just check if Username SESSION is set. But, I have come to notice something strange while putting another user through:
If we click the same link at the same time and arrive on the landing page same time, I noticed I can see my Username displayed as his Username and his personal data like email and phone replaced mine in my very own PC! This is really strange to me as we do not even live in the same country or even share same PC.
So, it is obvious I have not secured my SESSION and I have used a lame approach without thinking about security and this can be abused with SESSIONS hijacked.
How do I resolve this conflict? How do I restrict each logged in user to a particular session without conflicts if two or more users access the same resource at the very same time? I need help. I can't sleep since I found this.
After reading your responses, I will now show a snippet of the functions.php file which outputs Use data from DB.
First, I get the UserName value from session using:
$UserName = $_SESSION['Username'];
With this value, I query DB to get more user details:
//------------Get User Info -- All user column
$Get_User_Info = mysqli_query($conn,"SELECT * FROM customers WHERE User='$UserName'");
/************************************************************/
/************************************************************/
$Get_User_Info_row = mysqli_fetch_array($Get_User_Info,MYSQLI_ASSOC);
/************************************************************/
//---- Now list all user rows
$GLOBALS['Skype'] = $Get_User_Info_row['Skype'];
$GLOBALS['Jabber'] = $Get_User_Info_row['Jabber'];
$GLOBALS['ICQ'] = $Get_User_Info_row['ICQ'];
$GLOBALS['Join_Date'] = $Get_User_Info_row['Join_Date'];
$GLOBALS['Join_Date_Time'] = $Get_User_Info_row['Join_Date_Time'];
$GLOBALS['Balance'] = number_format($Get_User_Info_row['Balance'],2);
The above is what is contained in the functions.php which I require with each page I need protected.
As you can see, I barely see where I have done too much wrong there.
I want to know how I would get user 'McKenzie' to see his own unique page that he can manipulate and 'Wendy' to see her own page when she logs in.
I've created the login and the pages, connected them to a MySQL database given them ID's etc, so I can do all of this and I know about sessions etc. ;)
So can someone tell me how I would do this, would I have to make different pages for each separate user? I'm thinking something along the lines of
REGISTER PAGE:
Store data in database, get user ID and use "?pageid=1" to then take the user to the id based page.
But I'm not sure how I would make each page without making them manually, as you can imagine making a new page for each separate user would be a pain... and very inefficient. Any ideas?
And please show me an example with code, it would be GREATLY appreciated! Thank you all in advance!
My answer is assuming you want to create fully customizable user data with the added possibility of sharing the page between users (like a profile page). With that out of the way you can do this by creating one php page that searches the MySQL table by $_GET or $_POST data.
Ill expand this answer in to a couple of steps...
SQL Tables
The first thing you will need is your MySQL set-up, ill assume you have a basic set-up already done but I will go ahead and create a simple one.
The basic set-up will be the login data and the custom user data, you can view my set-up here.
php user page
The simplest way would be to get the requested user from the $_GET data. So to do this we would simply get the data and request the users information:
$requested_user = $_GET['id'];
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'root', 'MyPassword');
try {
$stmt = $db->prepare("SELECT * FROM c_userpage WHERE id = ?");
$stmt->execute(array($requested_user));
$mydata = $stmt->fetch();
} catch (Exception $e) {
//error with mysql
die();
}
Now we can simply add the users data to the page!
echo "Hello! my name is {$mydata['username']}!\n";
echo "About Me: {$mydata['custom_data']}";
Sending users to their page
We can simply just use www.page.com/user.php?id=2 And this will request the data for the user with id=2
Extras
If you want to keep user pages private you can simply request the id with $_POST or $_SESSION and then check if the user is logged in!
Full code for user.php
Full code for user.php w/ private page
Here's an example of what you could do:
<?php
if (!isset($_SESSION['user_id'])) && (!isset($_SESSION['user_name'])) {
echo '<p class="login">log in</p>';
//exit();
}
else {
$user_name = $_SESSION['user_name'];
echo('<p class="login">' . $user_name .'\'s page | Log out</p>');
}
?>
There's a lot more you could add, but this is just to generate information on whether they were logged in.. If the $_SESSION['user_id'] is set, you can then generate code based on that information. (note, you would need to create the $user_name or whatever variable, likely from an sql query)
Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something
I'm wondering if there's a way to dump all of the values of
$this->session->userdata()
so I can troubleshoot?
I'm working within Facebook, and have a login page, and once that's successful I want to pass around the UID of the current user, and I thought this would work well.
I currently have the uid set as follows:
require_once 'facebook.php';
$appapikey = 'XXXX';
$appsecret = 'XXXX';
$facebook = new Facebook($appapikey, $appsecret);
$user_id = $facebook->require_login();
$this->db->like('uid', $user_id);
$this->db->from('users');
$has_signed_up = $this->db->count_all_results();
if ($has_signed_up == 0) {
redirect('/setup/signup/', 'location');
}
else {
$this->session->set_userdata('uid', $user_id);
redirect('/preferences/index/', 'location');
}
So the redirection occurs, and I have a very simple setup over at preferences/index:
echo "this is the preferences form <br />";
echo $this->session->userdata('uid');
echo $this->session->userdata('session_id');
And the result is an inscrutable:
this is the preferences form
858f500e167e359edc1942a96f3bac35
So it totally skips over the middle echo containing the uid. Am I not setting this correctly? Is there a way to dump all values of the session array to see what's getting through? Any help would be just great.
UPDATE
I have run var_dump($this->session->userdata) on each the raw website and through Facebook.
On the website it exposes all set values in an array containing 5 values (session_id, IP, User_agent, last_activity, and uid).
Within the Facebook chrome however, it only shows the 4 values set by CodeIgniter. I've heard cookies can only be 4k and that encryption could be a problem. Could FB be filling up cookies with its own encrypted (read:larger) data?
UPDATE 2
When I comment out the redirect, and just have:
else {
$this->session->set_userdata('uid', $user_id);
echo ':test_'.$this->session->userdata('uid').'_test:';
//redirect('/preferences/index/', 'location');
}
It dutifully returns :test_1234_test: within Facebook. So somewhere during the redirect it's losing this part of the array (but not the whole array).
Is it possibly just creating a new session on the redirect page? So that's why it only has the four "stock" variables? If this is the case, I'll need to research how it creates the sessions, and if Facebook clears cookies I suppose.
UPDATE 3
So I've turned to using a DB to store session information instead of cookies, thinking FB was either stripping them or colliding with them. I currently have the app set up to
Set $user_id = 1234
$this->session->set_userdata('uid', $user_id)
Redirect to the new page
Var_dump all possible information
What occurs in the DB is this:
DB records http://nikolausjj.facebook.joyent.us/Picture2.png
So it creates one good record, with the user data, then immediately upon the redirect creates a new session without recognizing the prior one. Can someone explain where the CI framework checks to see if it has a prior session existing? The user manual explains it as "magic" basically.
You can use var_dump() to output the session. Something like this
var_dump($this->session);
The set_userdata call looks ok. Are you sure $user_id is set. Because the echo is surley executed but uid isn't set or set to empty string.
Try replacing the echo with
echo ':test_'.$this->session->userdata('uid').'_test:';
Other information helpful for answering
What browser are you using?
Do you have an underscore _ in your domain name?
Are you using CI sessions or some wrapper for native PHPsessions
Is the value for uid also lost/not set when you comment out the redirect?
Other suggestions:
try redirect('/preferences/index/', 'refresh'); instead of location
I'm not familiar with facebook development but is /preferences/index under your control? If yes try removing (if present) $this->load->library(‘session’) and instead load it in autoload.php.
try changing $config[‘sess_match_ip’] to `FALSE
try setting $config[‘sess_encrypt_cookie’] to FALSE
try replacing the use of CI-Session with CI Native session
Is UID sensible information if not store it in a cookie. If it matters if it can be spoofed don't.
I didn't solve how to pass session variables from one page to another via Facebook. My solution was simply to call the Facebook API for the user's UID again on each page. Not great programming, but it works alright for me. :-/