Giter VIP home page Giter VIP logo

php-mysql-sessions's Introduction

PHP-MySQL-Sessions

This is a native solution to easily store PHP session data in a MySQL database.

Overview

Session variables contain data that is saved for a specific user by associating the user with a unique identity. Typically, PHP would store session variables in a local file system on the server by default. While this may be acceptable to many people who are running small to moderate PHP applications, some larger applications that require load balancing would need to be run on multiple servers with a load balancer. In such cases, each server running PHP would need a way to ensure that sessions continue to work properly. One common way to achieve this is to override where PHP opens, reads, writes, and destroys the session variables so that it can perform these operations on a table inside of a MySQL database. When this is performed, the web application can gain advantages such as session management, session logging, and session interactions.

Installation

This solution can be easily integrated with your existing PHP code that uses PHP sessions. Simply perform the following steps:

  1. Upload the files in this repository to your Apache server running PHP. You can store these files inside any resource folder of your desire. It is not recommended that these files be located in the root directory since it contains some sensitive database information.

  2. Create a new MySQL database if you do not already have an existing one. Note down your MySQL credentials. Go to PHPMyAdmin or your database manager and run the following command:

    CREATE TABLE sessions
    (
    	id varchar(32) NOT NULL,
    	access int(10) unsigned,
    	data text,
    	PRIMARY KEY (id)
    );
  3. Edit the file database.class.php and change the following variables to your existing database.

    define("DB_HOST", "localhost");
    define("DB_USER", "yourusername");
    define("DB_PASS", "1234567890");
    define("DB_NAME", "yourdbname");
  4. Make sure PHP has sufficient privileges and make sure that your MySQL server accepts connections if separate from your localhost.

Usage

An example script called example.php has been provided for your convenience. This contains all the basic functionality you would need for storing, retrieving, and destroying a session. One thing to note is that you do not have to call session_start() on your code as that is already taken care of inside the mysql.sessions.php class.

  1. Declarations (include these on the top of your PHP):

    include("database.class.php");	//Include MySQL database class
    include("mysql.sessions.php");	//Include PHP MySQL sessions
    $session = new Session();	//Start a new PHP MySQL session
  2. Storing in a session variable:

    //Store variable as usual
    $_SESSION['user'] = "[email protected]";
  3. Retrieving session variable:

    //Show stored user
    echo $_SESSION['user'];
  4. Unset and Destroy (use these for signing out a user):

    //Clear session data (only data column)
    session_unset();
    //Destroy the entire session
    session_destroy();

Troubleshooting

If for some reason your code does not work, you can add the following lines to the top of your PHP script to show the errors:

error_reporting(E_ALL);
ini_set('display_errors', '1');

In addition, use PHPMyAdmin or your database manager to check your sessions table to see if the table has been altered in any way. For example, the table should populate as more session variables are being added.

php-mysql-sessions's People

Contributors

dominicklee avatar kurairaito avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-mysql-sessions's Issues

$Max duration

Hello,
Nice job thinks a lot.
It's seems to work on declarnig $session = new Session($max) instead of session_start() in every page (+dependencies).
But how do you define $Max duration?

Bots (friendly) executes the session class and creates new db rows every second

My IT department are running a monitoring system that checks for errors etc, and that script runs every second and generates a new session class initialization, which in turn creates a new row in the database. That's one new row every second!

My IT department can't do much about this on their end. Do you have an idea on how I can attack this problem? I think this happens since the class constructor executes all functions and I need to initiate the class on my index.php to check if a user is logged in or not, and that's the page the monitoring system looks at. Can empty rows (with empty data column) be deleted automatically or can a new row only be created when I run my login script?

On my localhost I don't have this issue. Otherwise the code works great! :)

unable to regenrate id

Normal session is working absolutely fine. However when I try to regenerate id(session_regenerate_id()) it gives error unable to read which is very obvious it failed to update record and look for new session id which is not even exist.

Warning: session_start(): Failed to read session data: user (path:)

I couldn't make this code work with both the latest stable PHP7.2.2 and PHP7.1.X.

I also had the --enable-fpm with compilations. It showed this error Warning: session_start(): Failed to read session data: user (path:).
I also tried to override default session manager with implements \SessionHandlerInterface which returned same error. Then I started doubting some compatibility issues of 7.2 and 7.1 with session_set_save_handler, but can't find any proof and not much time dig in as of now.

I could make it work with PHP7.0.X. builds with no problem!

Usage among multi pages

Thank you first for the nice and clean code!

But I have a question here. When trying to access session data among multiple pages application, do I need to include the new Session() statement every time?

Let's say on the login page, I have the DB & Session file included and $session=new Session(); executed. Then on the admin page I want to echo the stored $_SESSION['username'], I believe I also need to include the two files but do I need to run the new Session() again then echo the $_SESSION['username']?

Actually I tried both, both get me empty returned. The only difference is if I run the new session again, the session value in the database will be cleared and otherwise, it will just remain untouched. So I'm a little confused here.

Thanks again for your help~!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.