I googled to solve my question but any site explains my problem in a different way so I feel very confused!
I realized a php site in this way.
index.php:
In this page I get username and passw from login form and after checked if the user really exist I'll save them first in a variable and after in session.
$_SESSION['user']=$user;
$_SESSION['psw']=$psw;
Now I would show this page ONLY if the user is logged, so I would make some like this:
first_page.php:
<?
if(isset($_SESSION['user']) && isset($_SESSION['user'])!="" && isset($_SESSION['psw']) && isset($_SESSION['psw'])!=""{
// show page site
}
else
// go to index.php
?>
and insert this block if-else in any pages of the site.
It is correct this procedure?
I need to introduce session_start(); in any page or just in index.php?
How long time $_SESSION['user'] and $_SESSION['psw'] (expires)?
Since the site needs $_SESSION['user'] for many features, I need to be sure that when a user navigate the site those session variables are setted.
Thanks for your support, I feel very confused on it.
You must add session_start() in every single page where you use $_SESSION. It expires when you leave the site.
Don't store a password in a session, without changing the session handler data in a session is stored as plain text outside of the web root. This means anyone that has access to the system can read session data.
The method of knowing if a valid login occured is:
$sql = "select id where username = 'username' and password = 'hashedpassword'"
If an id is returned it means the user successfully logged in and store that ID in a session. Then validate if the session continues if the ID is set.
Keep in mind that after raising privileges it is recommend to change the session id as well, that can be done with session_regenerate_id() this to add protection for session fixation attacks.
At the beginning of each script when trying to read data from a session use session_start() and session_destroy() to remove all data stored in that session (usually a logout)
If I introduce at the top of any page the following script, could be a good solution? Or there's something wrong?
if ((isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) || $_SESSION['iduser']==NULL) {
// last request was more than 30 minutes ago
session_unset();
session_destroy(); // destroy session data in storage
echo "<script>location.href='index.php'</script>"; //redirect the user to index page
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
/* Code for the rest of my page HTML*/
(took from here: How do I expire a PHP session after 30 minutes?)
Related
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.
Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even access the session, even if I know it already exists.
I've read to user session_id() to find out if a session exists, but since I have to use session_start() before calling session_id(), and session_start() will create a new ID if there isn't a session, how can I possible check if a session exists?
In PHP versions prior to 5.4, you can just the session_id() function:
$has_session = session_id() !== '';
In PHP version 5.4+, you can use session_status():
$has_session = session_status() == PHP_SESSION_ACTIVE;
isset($_SESSION)
That should be it. If you wanna check if a single session variable exists, use if(isset($_SESSION['variablename'])).
I find it best many times (depends on the nature of the application) to simply test to see if a session cookie is set in the client:
<?php
if (isset($_COOKIE["PHPSESSID"])) {
echo "active";
} else {
echo "don't see one";
}
?>
Of course, replace the default session name "PHPSESSID" with any custom one you are using.
In PHP there is something called the session name. The name is co-related to the cookie that will be being set if the session was already started.
So you can check the $_COOKIE array if there is a session cookie available. Cookies are normally the preferred form to interchange the session id for the session name with the browser.
If a cookie already exists this means that a PHP session was started earlier. If not, then session_start() will create a new session id and session.
A second way to check for that is to check the outgoing headers if the cookie for the session is set there. It will be set if it's a new session. Or if the session id changed.
isset($_SESSION) isn't sufficient because if a session has been created and destroyed (with session_destroy()) in the same execution, isset($_SESSION) will return true. And this situation may happen without your knowing about it when a 3rd party code is used. session_id() correctly returns an empty string, though, and can be called prior to session_start().
Check if session exists before calling session_start()
if(!isset($_SESSION))session_start();
You can call session_id before session_start. http://www.php.net/manual/en/function.session-id.php - read the id param
I've always simply used
if (#session_id() == "") #session_start();
Hasn't failed me yet.
Been quite a long time using this.
NOTE: # simply suppresses warnings.
Store the session_id in $_SESSION and check against it.
First time
session_start();
$_SESSION['id'] = session_id();
Starts a session and stores the randomly given session id.
Next time
session_start();
$valid_session = isset($_SESSION['id']) ? $_SESSION['id'] === session_id() : FALSE;
if (!$valid_session) {
header('Location: login.php');
exit();
}
Starts a session, checks if the current session id and the stored session id are identical (with the ternary ? as replacement for the non-existing short circuit AND in php). If not, asks for login again.
switch off the error reporting if noting is working in your php version put top on your php code
error_reporting(0);
I solved this three years ago, but I inadvertently erased the file from my computer.
it went like this. 3 pages that the user had to visit in the order I wanted.
1) top of each php page
enter code heresession start();enter code here
2) first page:
a) enter code here$_session["timepage1"] = a php date function; time() simple to use
b) enter code here$_session["timepage2"]= $_session["timepage1"];
b) enter code here$_session["timepage3"]=$_session["timepage1"];
3) second page:
a) enter code here$_session["timepage2"] = a php date function; time() simple to use
b) enter code here$_session["timepage3"]= $_session["timepage3"];
3) third page:
a) enter code here$_session["timepage3"] = a php date function; time() simple to use
the logic:
if timepage3 less than timepage3 on page 2
{the user has gone to page 3 before page 2 do something}
if timepage2 on page 2 less than timepage1
{the user may be trying to hack page two we want them on page 1 do something}
timepage1 should never equal timepage2 or timepage3 on any page except page1 because if it is not greater on pages two or three the user may be trying to hack "do something"
you can do complex things with simple arithmetic with the 3 timepage1-2-3 variables. you can either redirect or send a message to say please go to page 2. you can also tell if user skipped page 2. then send back to page 2 or page one, but best security feature is say nothing just redirect back to page1.
if you enter code hereecho time(); on every page, during testing, you will see the last 3 digits going up if you visit in the correct order.
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.
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.
Is it possible to unset a specific user session (one who is banned from the site)?
Each session contains the user's username.
Or is the only way to writing sessions in the database and checks whether the user is deleted from that record?
Thanks for any suggestion.
PHP doesn't keep track of what session IDs have been issued - when a session cookie comes in on a request and session_start() is called, it'll look in the session save directory for a file named with that session's ID (sess_XXXX) and load it up.
Unless your login system records the user's current session ID, you'll have to scan that save directory for the file that contains the user's session, and delete the file. Fortunately, it could be done with something as simple as:
$session_dir = session_save_path();
$out = exec("rm -f `grep -l $username $session_dir/*`");
You'd probably want something a bit more secure/safe, but that's the basics of it.
Just remove the user from your database.
I assume that you are checking login credentials.
You can add a timeout to your sessions like so:
define('SESSION_EXPIRE', 3600 * 5); //5 hours
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > SESSION_EXPIRE) {
session_regenerate_id(true); // change session ID for the current session an invalidate old session ID
session_destroy();
session_start();
$_SESSION['CREATED'] = time(); // update creation time
}
I think the best method would be before allowing the user to comment, have PHP read your database and check if the individual has publish permissions. If not return an error.
Another thing you could do, which Facebook does, is have an AJAX call checking a PHP file every few minutes. The PHP file simply returns whether the user is logged on or off and if they are logged off, Javascript redirects them off the page.