I'm doing a little server-side project, where I need to check if a session variable is set, using session id's that are stored in my database.
The problem I'm getting, is that I don't want to destroy the session after I've checked if the variable is set. So I need a way to either check the variable without having to start the session, or find a way to change to a different session id while the session is started,
or duplicate the session to a different session that I can destroy.
Here's what I have:
while(true) {
$stmt=$db->prepare("SELECT sessionid FROM sessions");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC) {
session_id($row['sessionid']);
session_start();
if(!isset($_SESSION['value'])) {
$stmt=$db->prepare("DELETE FROM sessions WHERE sessionid=:sessionid");
$stmt->bindValue(':sessionid',$row['sessionid'],PDO::PARAM_STR);
$stmt->execute();
}
session_destroy();
}
sleep(5);
}
Done it Lol ...
while(true) {
$stmt=$db->prepare("SELECT sessionid FROM sessions");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC) {
session_id($row['sessionid']);
session_start();
session_regenerate_id(false);
$newsessionid=session_id();
session_write_close();
session_id($newsessionid);
session_start();
if(!isset($_SESSION['value'])) {
$stmt=$db->prepare("DELETE FROM sessions WHERE sessionid=:sessionid");
$stmt->bindValue(':sessionid',$row['sessionid'],PDO::PARAM_STR);
$stmt->execute();
}
session_destroy();
}
sleep(5);
}
Reference: http://uk1.php.net/manual/en/function.session-regenerate-id.php
Related
I have this in my session
<?php
session_start();
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
header("location: index.php");
exit;
}
?>
how can I calling other column which is user_id as session and insert into new table as current user that do insert action.
Yes, it is possible to create $_SESSION variables, it is fairly easy and straight forward. They are each element arrays.
You mentioned in your question that you wanted the user_id session variable, so just create the session array with the key of user_id.
$_SESSION['user_id'] = USER_ID;
$_SESSION['username'] = USER_NAME;
$_SESSION['email'] = USER_EMAIL;
//...
For more information on how to work with $_SESSION variables read PHP's Manual.
At the moment I am writing a little media library in PHP and i want to set sessions, so the user stays logged in and get's echoed his name at the front page.
[index.php]
if(isset($_SESSION['loggedin']))
{
//ECHO $USERNAME
}else{
echo '<p>To start, please login or register.</p>';
}
?>
I want, if theres an session id set, that PHP echoes out the $username.
[signup.php]
<?php
session_start();
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
$uid = ($_POST['uid']);
$pw = ($_POST['pw1']);
$pw2 = ($_POST['pw2']);
if ($pw == $pw2) {
$sql = "INSERT INTO user (uid, pw) VALUES ('$uid', '$pw')";
$result = mysqli_query($conn, $sql);
echo "Registration succeeded.";
}else{
echo "Please check your information.";
}
header ("Refresh: 3; ../index.php");
So, after PHP successfully compares my $pw1 and $pw2 i want to start a session, then it should put the $username in the $_SESSION array.
Of course next to the secure session id.
I repeat, after this i want to echo the $username out at front page.
What is the best way to do it?
Thanks.
$sql="SELECT username FROM users WHERE userid=$uid";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($result);
$_SESSION['username']=$row['username'];
You can do something like this.
Usage of $_SESSION super global array (compact version)
session_start(); //To init
$_SESSION['username'] = 'Bob'; // Store value
echo $_SESSION['username']; // Treat like normal array
Detailed example
To use a session, you have to init it first.
session_start();
After that you access the session vars via the super global
$_SESSION
A good way is always to store a value in your variables you want to use:
// init session
session_start();
// check if session var is set, if not init the field with value in the super global array
if(!isset($_SESSION['auth'])) $_SESSION['auth'] = false;
if(!$_SESSION['auth']) {
//do auth here like eg.
header('Location: signup.php'); // if auth is okay -> $_SESSION['auth] = true + redirect to this (main) script
die(); // This is really necessary because a header redirect can be ignored.
}
// if auth okay, do fancy stuff here
For security read the following
Remember to escape your user input, always!
How can I prevent SQL injection in PHP?
The session_id is stored in cookies normally.
Or - the old way via URL parameter.
You do not have to secure the session_id.
Read also advices about XSS/CSRF.
Plus tokens are also good.
May be this is what you mean with secure session_id.
Stackoverflow: preventing csrf in php
OWASP: https://www.owasp.org/index.php/PHP_CSRF_Guard
OWASP: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
Hello I have question about updating mysql db field with enum 1 and 0 and when the user log in it change it to 1 but when user log out i tried doing this but it won't work...
Also I tried make it as button and if btn is pressed do something and then go to logout.php but it didnt work ...
So my code is this ...
<?php include_once('connect.php');
$logger = $_SESSION["login"];
session_start();
session_unset();
session_destroy();
$mysqli = "UPDATE table SET field='0' WHERE email='$logger'";
if(mysqli_query($con, $mysqli)){
header("Location: index.php");}else echo "Something went wrong!";
?>
Your issue isn't to do with the other two answers, #Gopal states that you should destroy after unsetting the session, however you are setting the variable before unsetting the session. #Marmik also doesn't solve the issue.
Your problem lies here:
$logger = $_SESSION["login"];
session_start();
You're trying to access the session variable before you actually start the session. This is going to give you a blank $logger which you may find if you use echo $logger.
So, how do we solve this. Essentially, we just swap two lines around, so that session_start() is before we try accessing the session variables.
session_start();
$logger = $_SESSION["login"];
If this fails, you may want to check that $_SESSION["login"] has actually been set in the first place with a quick echo $_SESSION['login']; after session_start();
Good luck!
Give session_unset(); session_destroy(); After update query of the table.
what you can do is you can check the session that he is really logedin or not
On Logout.php
<?php
#session_start();
if(!empty($_SESSION['login'])){
include_once('connect.php');
$logger = $_SESSION["login"];
$mysqli = "UPDATE table SET field='0' WHERE email='$logger'";
if(mysqli_query($con, $mysqli)){
session_unset();
session_destroy();
header("Location: index.php");
}
else {
echo "Something went wrong!"
};
}
?>
I'm getting an error using session_destroy() in my PHP code.
The following script is on every page and if a user is signed in, it checks if the session is valid or not, killing the session if it's not.
session_start();
// check for users already signed in and check session
if (isset($_SESSION['user_id'])) {
$uid = $_SESSION['user_id'];
// check user_id is a valid id
if (!is_numeric($uid) || $uid < 0) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
// if user agent is different, kill session
if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
// if user's last login record fails to match session_id, kill session
$SQL = "SELECT user_session FROM users_logins ";
$SQL .= "WHERE user_id = :user_id ";
$SQL .= "ORDER BY time_in DESC LIMIT 1;";
$STH = $DBH_P->prepare($SQL);
$STH->bindParam(':user_id', $uid);
$STH->execute();
$row = $STH->fetch();
if ($STH->rowCount() > 0) {
$db_sid = $row['user_session'];
}
if ($db_sid !== session_id()) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
}
The error I receive indicates the failure is coming from the last session_destroy() call.
Am I using session_destroy() correctly or not? I have read other questions on here but most answers advise that session_start() must be used before destroying it, but I have started the session at the top, before the check begins.
You do some crazy stuff there (but you need to negotiate that with your own, I don't cover it in my answer), the reason why you see the error message is quite simple:
session_regenerate_id(true);
is commanding PHP to destroy the old session. Problem is, you already did that, one line earlier:
session_destroy();
session_regenerate_id(true);
So just take a view from above. There is no reason in an OCD manner to throw as many functions as you see fit (but actually don't understand/know well) onto your session processing. Instead take the one function that is intended to do the job and actually process it's return value if you want to put some safety net in there actually. That would be more helpful.
i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? » Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.