What is the best way to store secure user data in php sessions?

Asked
Active3 hr before
Viewed126 times

8 Answers

securestore
90%

Assuming you don't need to preserve session data across a database restart, you could also make the session store table's storage engine to be MEMORY instead of Innodb or MyISAM. This will make it pretty snappy and avoid the concern you might have of session data being inside the db files on disk in an unencrypted state.,If you store the private key anywhere on the server, then it's only as safe as your trust in anyone who has root access to that server. For a secure messaging system, not all your users may want to trust the people who can access root. (Do they?) That suggests you'd want to store the private key on the user's machine. As you suggested, doing that is a whole different set of security questions.,The problem is that I need to maintain a non-encrypted version of the private key in the user's session to make sure he is able to read every message and write new messages without inserting the password on every page refresh.,Storing in the PHP Session is not a secure solution since the PHP Sessions are still stored on the server and can be compromised.

Assuming you have full control and can limit access/visibility to your database, you can switch over storing your session data from file storage to using database as session store. This assumes of course your db is secure enough for your needs. You can check out a detailed overview on how to setup php for storing session to your database here: http://www.stanford.edu/dept/its/communications/webservices/wiki/index.php/How_to_use_MySQL-based_sessions

Assuming you don't need to preserve session data across a database restart, you could also make the session store table's storage engine to be MEMORY instead of Innodb or MyISAM. This will make it pretty snappy and avoid the concern you might have of session data being inside the db files on disk in an unencrypted state.

MEMORY
88%

This screenshot shows the UI for the secured Remember Me with a login form.,Import this SQL script to test this example in your local environment. After set up, try login with admin/admin as the username and the password.,I have created a login form to get the username and password. This form contains a checkbox captioned as ‘Remember Me’ to allow the user to preserve his logged in status. When the user submits the login data, the posted details are received in PHP and validated with the member database.,On successful login, if the user selected ‘Remember Me’ then the logged-in status is stored in PHP session and cookies.

As it is a security loophole to store the plain password in the cookie, the random numbers are generated as the authentication keys. These keys are hashed and stored in the database with an expiration period of 1 month. Once the time expires, then the expiration flag will be set to 0 and the keys will be deactivated.

< ? php
session_start();

require_once "Auth.php";
require_once "Util.php";

$auth = new Auth();
$db_handle = new DBController();
$util = new Util();

require_once "authCookieSessionValidate.php";

if ($isLoggedIn) {
   $util - > redirect("dashboard.php");
}

if (!empty($_POST["login"])) {
   $isAuthenticated = false;

   $username = $_POST["member_name"];
   $password = $_POST["member_password"];

   $user = $auth - > getMemberByUsername($username);
   if (password_verify($password, $user[0]["member_password"])) {
      $isAuthenticated = true;
   }

   if ($isAuthenticated) {
      $_SESSION["member_id"] = $user[0]["member_id"];

      // Set Auth Cookies if 'Remember Me' checked
      if (!empty($_POST["remember"])) {
         setcookie("member_login", $username, $cookie_expiration_time);

         $random_password = $util - > getToken(16);
         setcookie("random_password", $random_password, $cookie_expiration_time);

         $random_selector = $util - > getToken(32);
         setcookie("random_selector", $random_selector, $cookie_expiration_time);

         $random_password_hash = password_hash($random_password, PASSWORD_DEFAULT);
         $random_selector_hash = password_hash($random_selector, PASSWORD_DEFAULT);

         $expiry_date = date("Y-m-d H:i:s", $cookie_expiration_time);

         // mark existing token as expired
         $userToken = $auth - > getTokenByUsername($username, 0);
         if (!empty($userToken[0]["id"])) {
            $auth - > markAsExpired($userToken[0]["id"]);
         }
         // Insert new token
         $auth - > insertToken($username, $random_password_hash, $random_selector_hash, $expiry_date);
      } else {
         $util - > clearAuthCookie();
      }
      $util - > redirect("dashboard.php");
   } else {
      $message = "Invalid Login";
   }
} ?
>
load more v
72%

The session module can not guarantee that the information stored in a session is only viewed by the user who created the session. Additional measures are needed to protect the confidentiality of the session, depending on the value associated with it. , Obsolete session data must be inaccessible and deleted. The current session module does not handle this well. , If a user accesses an obsolete session (expired session), access to it should be denied. It is also recommended to remove the authenticated status from all of the user's sessions to as it is likely to represent an attack. , The current session module does not detect any modification of $_SESSION when the session is inactive. It is the developer's responsibility not to modify $_SESSION when the session is inactive.

The session module can not guarantee that the information stored in a session is only viewed by the user who created the session. Additional measures are needed to protect the confidentiality of the session, depending on the value associated with it.

The importance of the data carried in the session needs to be assessed and further protection may be deployed; this typically comes at a price, such as reduced convenience for the user. For example, to protect users from a simple social engineering tactic, session.use_only_cookies needs to be enabled. In that case, cookies must be enabled unconditionally on the client side, or sessions will not work.

session.use_only_cookies
load more v
65%

If you add the above line in the .htaccess file, that should start a session automatically in your PHP application.,You can modify or delete session variables created earlier in the application in the same way as for regular PHP variables.,In this section, we’ll explore how to initialize session variables in PHP.,You can also learn about session variables in my post on using cookies in PHP.

This is the method that you'll see most often, where a session is started by the session_start function.

< ? php
// start a session
session_start();

// manipulate session variables
?
>
load more v
75%

This guide will show you how you can store your sessions securely in a mySQL database. We will also encrypt all session data that goes into the database, which means if anyone manages to hack into the database all session data is encrypted by 256-bit AES encryption. ,LOG IN Log in Social login does not work in incognito and private browsers. Please log in with your username or email to continue. Facebook Google wikiHow Account No account yet? Create an account ,Level up your tech skills and stay ahead of the curve, Question When and where do I call the open(), encrypt() and decrypt() functions? Community Answer You do not call these functions. These functions are for PHP to call itself. Thanks! Yes No Not Helpful 0 Helpful 9

CREATE DATABASE `secure_sessions`;
load more v
40%

Although you can store data using cookies but it has some security issues. Since cookies are stored on user's computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful data in your application that might break your application.,In this tutorial you will learn how to store certain data on the server on a temporary basis using PHP session.,Is this website helpful to you? Please give us a like, or share your feedback to help us improve. Connect with us on Facebook and Twitter for the latest updates.,Note: You must call the session_start() function at the beginning of the page i.e. before any output generated by your script in the browser, much like you do while setting the cookies with setcookie() function.

< ? php
// Starting session
session_start(); ?
>
load more v
22%

Cookies are small files saved on the user’s computer, Cookies can only be read from the issuing domain, Sessions are like global variables stored on the server, A session is a global variable stored on the server.

Let’s now look at the basic syntax used to create a cookie.

< ? php

setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);

?
>
load more v
60%

PHP Sessions security issues,Web applications need a way to preserve a context about the visitor – from logged-in user identity, shopping cart in ecommerce stores, to longer-lasting data like purchase history or chat history in social network applications.,The most common of all session exploits is Session Hijacking. ,So what are common-sense measures we can take to mitigate Session hijacking attacks?

PHP as a web programming language belongs to the application layer. PHP builds on HTTP cookies to provide a mechanism to maintain context across multiple requests. For this, it combines custom, specific cookie header with its own session handler class:

SessionHandler implements SessionHandlerInterface, SessionIdInterface {
   /* Methods */
   public close(): bool
   public create_sid(): string
   public destroy(string $id): bool
   public gc(int $max_lifetime): int | bool
   public open(string $path, string $name): bool
   public read(string $id): string
   public write(string $id, string $data): bool
}

Other "secure-store" queries related to "What is the best way to store secure user data in php sessions?"