How to fetch a user's id from a database in php? - php

I am working on a simple PHP web-application. And in that I want to get Id of user from the mysql database.
For that I have used session to store userID as soon as user in inserted in database:
session_start();
$_SESSION['customer_id']=mysqli_insert_id($con);
But it always says that undefined index customer_id on other pages.It is working fine on localhost but not on live server.

As per the documentation: mysqli_insert_id Returns the auto generated id used in the latest query. If you don't run an insert query before starting session, then mysqli_insert_id will not return what you're looking for.
Rather, try searching for the user with information obtained upon user login, like the user's email address or username.
E.g.
SELECT id FROM users WHERE users.username = userSuppliedEmail
It goes without saying that you should use prepared statements or some similar technology for this query.

It looks like something is preventing you from creating a session.
Before you do anything, where you declare session_start, do the following:
Instead of session_start() put:
$started = session_start();
echo "Session Started: " . ($started ? "YES" : "NO");
If PHP says the session is indeed started, make sure the session id is staying the same between requests. You can obtain the session id with:
echo session_id();
From request to request, the session id must be the same, unless it's expired, or deleted. If you get a session id on first page, but no session id on second page, then either session_start wasn't executed, or the session was not created.
Since you assured me session_start is executed, the next thing you need to do is verify that the session is indeed created, and written to a file on the server.
After you obtain the session id, (eg. 7815696ecbf1c96e6894b779456d330e) you should check your sessions folder for a file named 7815696ecbf1c96e6894b779456d330e (this is just an example, your file name will be different).
$sessionPath = ini_get('session.save_path'); // obtains the path to session
echo "Our session path is: $sessionPath <br/>";
$filesInSessionFolder = scandir($sessionPath); // obtain all files in session folder
if($filesInSessionFolder == false){
echo "Could not access session folder<br/>";
}else{
// display all files in the folder
print_r($filesInSessionFolder);
}
Now make sure that the session id exists in the list.

Related

PHP Session variables being unset

I've created a login which sets a session variable to the users id which I get from my database. After the user clicks login after entering their details I redirect them to the home page which uses the session variable to get the users id for display purposes. The problem I am having is with the session variable. This is what my code looks like (simplified):
$_SESSION['user_id'] = $User_id;
header('Location: http://localhost/Projects/Login/home.php');
exit();
This is the snippet of code which sets my session variable, I have tested an it works. The next snippet of code is the function which is called from the home page (home.php). It is used to check if the user is logged in or not
function logged_in(){
return isset($_SESSION['user_id']);
}
I then use this if statement to perform different displays based on whether the user is logged in or not, again it has been simplified.
if( logged_in() === true ){
$session_user_id = $_SESSION['user'];
print "logged in";
}
else{
print "not logged in";
}
The problem seems to be with the if statement as it unsets the session variable to an empty array. If I print out the session variable I get Array(). I have started a session on each of the pages.
There seem to be two issues here.
First is the array keys; you're using user in one case and user_id in the other.
The second is speculative; you said it results in an empty array (I assume you have var_dump($_SESSION) or similar to confirm this?). If so it suggests you haven't started the session. You need to call session_start(); to get access to the session data.
Each time your script runs it needs to get access to the sessions stored on the server, this is why you run session_start(). The long version is that it obtains a lock on the local file which stores the session data (leading to whats known as session locking). As a result you may (for longer running scripts and/or performance) wish to call session_write_close() when you're finished with the $_SESSION superglobal.

PHP Session Variable not Available

I have a PHP file (approvals.php) that only gets executed on an AJAX call. It has a postgresql query that searches a table and uses a customer id, which is set as a session variable. Problem is, it seems I can't access this session variable in this file. My query is like:
$query = "SELECT merchant_id FROM ndovu_merchant_users WHERE customer_id={$_SESSION['customer_id']}";
$result = pg_query($query);
I have tried to echo the session variable $_SESSION['customer_id'] but nothing. However on passing a fixed value to the query, it returns a result.
In your case, i would have checked if the session is set in the first place.
//this should be put at the header of the page
session_start();
if(isset($_SESSION['customer_id']) && !empty($_SESSION['customer_id'])){
echo $_SESSION['customer_id'];
}else{
echo 'session is not set';
}
You need to place session_start(); above the code section where you use it; the top of the page is usually the best place to place it.
Also, it should be noted; you have what is potentially a large security flaw here, by passing in unescaped data.
You should look into using prepared statements if possible; or at least escape your inputs.
The user session is not accesed when the script is called by an ajax request.
The session token wich php requires to obtain the session data is stored in the client side(user) inside a session cookie.
You can read more here
https://stackoverflow.com/a/1535712/3922692
Just pass the user id with GET or POST in the ajax request.
There is not enough code presented but if you realy need to get the id from the session you can use an iframe (which is not recommended), process fetch data server side and output it in the iframe.

session set in folders php mysql

i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

Force user to logout session PHP

I can't seem to find a straightforward answer to this question. Is there a way in which I can force a logged in user to logout? My login system essentially just relies on a session containing the user's unique ID (which is stored in a mysql database). So essentially just...
if (isset($_SESSION['user_id'])) {
echo "You're logged in!";
} else {
echo "You need to login!";
}
But let's say I want to ban this user, well I can change their status to banned in my database but this won't do anything until the user logs out and attempts to log back in... So, how do I force this user to logout? Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server. Any help is appreciated, thank you.
Either you need to check every time they load a page, or possibly look at an Ajax call at set intervals to check their status from the DB.
Then you can use session_destroy(); to end their session. This will destroy their entire session.
Otherwise you can use unset($_SESSION['user_id']); to unset a single session variable
Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server.
Loading the user from the database on every page load, rather than storing a copy of the user in the session, is a perfectly reasonable solution. It also prevents the user from getting out of sync with the copy in the database (so that, for instance, you can change a user's properties or permissions without them having to log out and back in).
Try to put this on every page...
if (isset($_SESSION['user_id'])) {
$sql = "SELECT from tbl where status='banned' and user_id=$_SESSION['user_id'] ";
$query = mysql_query($sql);
if(!empty(mysql_num_rows($query))){ // found the banned user
//redirect to logout or
//session_destroy();
}
} else {
echo "You need to login!";
}
if the user is still logged in... check if his/her status is banned or not... if banned.. then logout
You can unset it.
unset($_SESSION['user_id'])
You could use Custom Session Handlers this way you have full control where and how the session data is stored on the server.
So you could store the session data for a particular user in a file called <user_id>.session for example. Then, to logout the user, just delete that file.
Ajax calls in an interval will put extra load on server. If you want real-time response to your actions(e.g. the user will be signed out right when you ban them from your system backend), then you should look into something like Server Push.
The idea is to keep a tunnel open from Server to Browser whenever a user is browsing your website, so that you can communicate with them from server-side too. If you want them to be banned, push a logout request and the process that in your page(i.e. force logout by unsetting session).
This worked for me am using pHP 5.4
include 'connect.php';
session_start();
if(session_destroy())
{
header("Location: login.php");
}
You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().
Once you delete the session file stored in the sever, the client side PHPSESSID cookie will no longer be valid for authentication and the user will be automatically be logger out of your application.
Please be very careful while using this approach, if the path in question turns out to be the global /tmp directory! There's bound to be other processes other than PHP storing temporary data there. If PHP has its own directory set aside for session data it should be fairly safe though.
There is a few ways to do this the best in my opinion based on security is:
NOTE: THIS IS REALLY ROUGH.... I know the syntax is wrong, its just for you to get an idea.
$con = mysql_connect("localhost","sampleuser","samplepass");
if (!$con)
{
$error = "Could not connect to server";
}
mysql_select_db("sampledb", $con);
$result = mysql_query("SELECT * FROM `sampletable` WHERE `username`='".$_SESSION['user_id']."'");
$userdeets = mysql_fetch_array($result);
if($_SESSION['sessionvalue'] != $userdeets['sessionvalue'])
{
session_destroy();
Header('Location: logout.php');
}
else
{
$result2 = mysql_query("UPDATE `sessionvalue` WHERE `username`='".$_SESSION['user_id']."' SET `sessionvalue` = RANDOMVALUE''");
$sesval = mysql_fetch_array($result2);
$_SESSION['sessionvalue'] = $seshval
}
Now I know thats not the very code but in essence what you need to do to be secure and have this ability is:
Everytime a page load check a Session value matches a value in the DB.
Every time a page loads set a new session value based on a random generated DB value. you will need to store the username in a session as well.
if the Session ID's do not match then you destroy the session and redirect them.
if it does match you make the new session ID.
if you want to ban a user you can set their sessionvalue in the DB to a value like "BANNED". this value will not allow them to log in either. this way you can control user through a simple web form and you can also generate list of banned users very easily etc etc. I wish I had more time to explain it I hope this helps.

Jump to another existing session (using PHP's default session handler)

I have a scenario like this:
UserJoe has session_id abc123 abc123 is stored in UserJoe's row in the users table in the DB.
UserJoe calls AdminBob and reports a problem.
AdminBob needs to experience UserJoe's problem first hand
So, I'd like to do something like:
01| $sessionId = getSessionId("UserJoe");
02| changeToExistingSession($sessionId);
03| if($_SESSION["name"] == "UserJoe") echo "successfully changed users";
Line 02 is where I'm kinda stuck... Any ideas?
(preferably not using session_save_path() anywhere :P)
EDIT: And it's just for the duration of the page execution. I'd like to keep AdminBob's session cookie intact.
If you store UserJoe's session ID in a database together with the report, then I think you can use session_id() to set AdminBob's session ID to UserJoe's session id.
<?php
if(!isset($_GET["id"]))
{
session_start();
$_SESSION["foobar"] = $_GET["bar"];
echo "Setting...";
var_dump($_SESSION);
var_dump($_COOKIE);
}
else
{
session_id($_GET["id"]);
var_dump($_GET["id"]);
var_dump($_COOKIE);
session_start();
var_dump($_SESSION);
}
?>
To test: Open this page in one browser and set bar to anything.
index.php?bar=blahblahblah
Open a new browser and visit the same page but do not set bar, get the value of PHPSESSID and set it as id's value
index.php?id=[value of PHPSESSID]
You should see the other browser's session in the newly opened browser

Categories