Skip to content

Commit

Permalink
Updated project files
Browse files Browse the repository at this point in the history
Finished initial readme and added PHP files
  • Loading branch information
Dominick Lee committed Feb 28, 2017
1 parent fcb0f28 commit c4cde68
Show file tree
Hide file tree
Showing 4 changed files with 317 additions and 17 deletions.
69 changes: 52 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,57 @@ This solution can be easily integrated with your existing PHP code that uses PHP

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:

```mysql
CREATE TABLE sessions
(
id varchar(32) NOT NULL,
access int(10) unsigned,
data text,
PRIMARY KEY (id)
);
```
```mysql
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.
```php
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.
```php
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.

- **Declarations** (include these on the top of your PHP):
```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
```
- **Storing in a session variable**:
```php
//Store variable as usual
$_SESSION['user'] = "johnsmith@example.com";
```
- **Retrieving session variable**:
```php
//Show stored user
echo $_SESSION['user'];
```
- **Unset and Destroy** (use these for signing out a user):
```php
//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:
```php
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.
105 changes: 105 additions & 0 deletions database.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

/*
Revised code by Dominick Lee
Original code derived from "Run your own PDO PHP class" by Philip Brown
Last Modified 2/27/2017
*/

// Define database configuration
define("DB_HOST", "localhost");
define("DB_USER", "yourusername");
define("DB_PASS", "1234567890");
define("DB_NAME", "yourdbname");

class Database{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;

public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}

public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}

public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

public function rowCount(){
return $this->stmt->rowCount();
}

public function lastInsertId(){
return $this->dbh->lastInsertId();
}

public function beginTransaction(){
return $this->dbh->beginTransaction();
}

public function endTransaction(){
return $this->dbh->commit();
}

public function cancelTransaction(){
return $this->dbh->rollBack();
}

public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}

public function close(){
$this->dbh = null;
}
}
?>
28 changes: 28 additions & 0 deletions example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

//Written by Dominick Lee
//Last Modified 2/27/2017

//Enable the below two lines to show errors:
//error_reporting(E_ALL);
//ini_set('display_errors', '1');

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


//Store variable as usual
$_SESSION['user'] = "johnsmith@example.com";

//Show stored user
echo $_SESSION['user'];

//The following functions are used for sign-out:

//Clear session data (only data column)
//session_unset();

//Destroy the entire session
//session_destroy();
?>
132 changes: 132 additions & 0 deletions mysql.sessions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

/*
Revised code by Dominick Lee
Original code derived from "Essential PHP Security" by Chriss Shiflett
Last Modified 2/27/2017
CREATE TABLE sessions
(
id varchar(32) NOT NULL,
access int(10) unsigned,
data text,
PRIMARY KEY (id)
);
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | varchar(32) | | PRI | | |
| access | int(10) unsigned | YES | | NULL | |
| data | text | YES | | NULL | |
+--------+------------------+------+-----+---------+-------+
*/


class Session {
private $db;

public function __construct(){
// Instantiate new Database object
$this->db = new Database;

// Set handler to overide SESSION
session_set_save_handler(
array($this, "_open"),
array($this, "_close"),
array($this, "_read"),
array($this, "_write"),
array($this, "_destroy"),
array($this, "_gc")
);

// Start the session
session_start();
}
public function _open(){
// If successful
if($this->db){
// Return True
return true;
}
// Return False
return false;
}
public function _close(){
// Close the database connection
// If successful
if($this->db->close()){
// Return True
return true;
}
// Return False
return false;
}
public function _read($id){
// Set query
$this->db->query('SELECT data FROM sessions WHERE id = :id');
// Bind the Id
$this->db->bind(':id', $id);
// Attempt execution
// If successful
if($this->db->execute()){
// Save returned row
$row = $this->db->single();
// Return the data
return $row['data'];
}else{
// Return an empty string
return '';
}
}
public function _write($id, $data){
// Create time stamp
$access = time();
// Set query
$this->db->query('REPLACE INTO sessions VALUES (:id, :access, :data)');
// Bind data
$this->db->bind(':id', $id);
$this->db->bind(':access', $access);
$this->db->bind(':data', $data);
// Attempt Execution
// If successful
if($this->db->execute()){
// Return True
return true;
}
// Return False
return false;
}
public function _destroy($id){
// Set query
$this->db->query('DELETE FROM sessions WHERE id = :id');
// Bind data
$this->db->bind(':id', $id);
// Attempt execution
// If successful
if($this->db->execute()){
// Return True
return true;
}
// Return False
return false;
}
public function _gc($max){
// Calculate what is to be deemed old
$old = time() - $max;
// Set query
$this->db->query('DELETE FROM sessions WHERE access < :old');
// Bind data
$this->db->bind(':old', $old);
// Attempt execution
if($this->db->execute()){
// Return True
return true;
}
// Return False
return false;
}
}
?>

0 comments on commit c4cde68

Please sign in to comment.