Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 19, 2023 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/f77031b8abd29b74ef9b4e1e6b84b632 to your computer and use it in GitHub Desktop.
Save code-boxx/f77031b8abd29b74ef9b4e1e6b84b632 to your computer and use it in GitHub Desktop.
PHP MYSQL Cross Domain Shared Session

PHP MYSQL CROSS-DOMAIN SHARED SESSION

https://code-boxx.com/cross-domain-session-php/

NOTES

  1. WARNING - Advanced topic. Study PHP cookies and sessions before you attempt to crack this one.
  2. Create a database and import 1-sess-db.sql.
  3. Change the database settings in 2-lib.sess.php to your own.
  4. Run unpack.bat (Windows) unpack.sh (Mac/Linux). This will automatically:
    • Create 2 folders a and b.
    • Move 3-index.php into a.
    • Move 4-sync.php and 5-index.php into b.
  5. In your HOSTS file, map site-a.com and site-b.com to 127.0.0.1 and/or ::1.
  6. Create 2 virtual hosts - https://site-a.com and https://site-b.com. Map https://site-a.com to a, and https://site-b.com to b.
  7. Access both https://site-a.com and https://site-b.com, make sure that they work.
  8. Access https://site-a.com/3-index.php - This will do a CORS fetch to https://site-a.com/4-sync.php.
  9. Open a new tab and access https://site-b.com/5-index.php - Both sites should now share the same PHP session ID.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `sessions` (
`id` varchar(64) NOT NULL,
`access` bigint(20) UNSIGNED DEFAULT NULL,
`data` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `sessions`
ADD PRIMARY KEY (`id`);
<?php
// (A) DATABASE SESSION CLASS
class MySess implements SessionHandlerInterface {
// (A1) PROPERTIES
private $pdo = null;
private $stmt = null;
public $error = "";
public $lastID = null;
// (A2) INIT - CONNECT TO DATABASE
public function __construct() {
$this->pdo = new PDO(
"mysql:host=".SDB_HOST.";charset=".SDB_CHAR.";dbname=".SDB_NAME,
SDB_USER, SDB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (A3) HELPER - EXECUTE SQL QUERY
function exec ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
$this->lastID = $this->pdo->lastInsertId();
}
// (A4) SESSION OPEN - NOTHING IN PARTICULAR...
function open ($path, $name) { return true; }
// (A5) SESSION CLOSE - CLOSE DATABASE CONNECTION
function close () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
return true;
}
// (A6) SESSION READ - FETCH FROM DATABASE
function read ($id) {
$this->exec("SELECT `data` FROM `sessions` WHERE `id`=?", [$id]);
$data = $this->stmt->fetchColumn();
return $data===false ? "" : $data ;
}
// (A7) SESSION WRITE - WRITE INTO DATABASE
function write ($id, $data) {
$this->exec("REPLACE INTO `sessions` VALUES (?, ?, ?)", [$id, time(), $data]);
return true;
}
// (A8) SESSION DESTROY - DELETE FROM DATABASE
function destroy ($id) {
$this->exec("DELETE FROM `sessions` WHERE `id`=?", [$id]);
return true;
}
// (A9) GARBAGE COLLECT - DELETE OLD ENTRIES
function gc ($max) {
$this->exec("DELETE FROM `sessions` WHERE `access` < ?", [(time() - $max)]);
return true;
}
}
// (B) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("SDB_HOST", "localhost");
define("SDB_CHAR", "utf8mb4");
define("SDB_NAME", "test");
define("SDB_USER", "root");
define("SDB_PASS", "");
// (C) START!
session_set_save_handler(new MySess(), true);
session_start();
<!DOCTYPE html>
<html>
<head>
<title>Sync Session</title>
<style>
* { font-family: Arial, Helvetica, sans-serif; box-sizing: border-box; }
h2 { color: #bb2b2b; }
form { width: 400px; padding: 20px; border: 1px solid #eee; background: #f5f5f5; }
label, input, textarea { border: 0; display: block; width: 100%; }
input, textarea { padding: 10px; }
textarea { height: 100px; resize: none; }
form label:first-child { margin-top: 0; }
label { margin: 10px 0; font-weight: 700; color: #4e86cd; }
</style>
</head>
<body>
<!-- (A) START PHP SESSION -->
<?php
require "../2-lib-sess.php";
$_SESSION = ["Start" => date("Y-m-d H:i:s")];
?>
<!-- (B) "INFORMATION DISPLAY" -->
<h2>THIS IS SITE A</h2>
<form>
<label>SESSION ID</label>
<input type="text" value="<?=session_id()?>" readonly>
<label>SESSION VAR</label>
<textarea readonly><?php print_r($_SESSION); ?></textarea>
<label>SESSION SYNC</label>
<div id="sync"></div>
</form>
<!-- (C) SESSION SYNC -->
<script>
// (C1) SITES TO SYNC
var sites = ["site-b.com"];
// (C2) HELPER - SHOW SYNC STATUS IN HTML
var rower = txt => {
let row = document.createElement("div");
row.innerHTML = txt;
document.getElementById("sync").appendChild(row);
};
// (C3) FORM DATA - PHP SESSION ID
var data = new FormData();
data.append("sid", "<?=session_id()?>");
// (C4) START SYNC
for (let site of sites) {
fetch(`https://${site}/4-sync.php`, {
mode : "cors", credentials : "include",
method : "post", body : data
})
.then(res => res.text())
.then(txt => rower(`https://${site}/ - ${txt}`))
.catch(err => rower(`https://${site}/ - ${err.message}`));
}
</script>
</body>
</html>
<?php
// (A) ALLOW CORS FROM SITE-A
header("Access-Control-Allow-Origin: https://site-a.com");
header("Access-Control-Allow-Credentials: true");
// (B) CHECK - PHP SESSION ID MUST BE SENT
if (!isset($_POST["sid"])) { exit("PHPSESSID not provided"); }
// (C) SET CROSS ORIGIN SESSION COOKIE
setcookie("PHPSESSID", $_POST["sid"], [
"path" => "/",
"domain" => "site-b.com",
"secure" => true,
"samesite" => "None"
]);
// (D) DONE
echo "OK";
<?php
// (A) DUMMY PROOFING - PHP SESSION MUST BE STARTED FROM SITE A
if (!isset($_COOKIE["PHPSESSID"])) {
exit("Please sync from site A first.");
} ?>
<!DOCTYPE html>
<html>
<head>
<title>Session Verification</title>
<style>
* { font-family: Arial, Helvetica, sans-serif; box-sizing: border-box; }
h2 { color: #bb2b2b; }
form { width: 400px; padding: 20px; border: 1px solid #eee; background: #f5f5f5; }
label, input, textarea { border: 0; display: block; width: 100%; }
input, textarea { padding: 10px; }
textarea { height: 100px; resize: none; }
form label:first-child { margin-top: 0; }
label { margin: 10px 0; font-weight: 700; color: #4e86cd; }
</style>
</head>
<body>
<!-- (B) START PHP SESSION -->
<?php
require "../2-lib-sess.php";
?>
<!-- (C) "INFORMATION DISPLAY" -->
<h2>THIS IS SITE B</h2>
<form>
<label>SESSION ID</label>
<input type="text" value="<?=session_id()?>" readonly>
<label>SESSION VAR</label>
<textarea readonly><?php print_r($_SESSION); ?></textarea>
</form>
</body>
</html>
md a
md b
move 3-index.php a
move 4-sync.php b
move 5-index.php b
mkdir -m 777 a
mkdir -m 777 b
mv ./3-index.php ./a
mv ./4-sync.php ./b
mv ./5-index.php ./b
127.0.0.1 site-a.com
127.0.0.1 site-b.com
::1 site-a.com
::1 site-b.com
<VirtualHost site-a.com:443>
DocumentRoot "D:\http\a"
ServerName site-a.com
SSLEngine On
SSLCertificateFile "C:/xampp/apache/conf/ssl.crt/server.crt"
SSLCertificateKeyFile "C:/xampp/apache/conf/ssl.key/server.key"
<Directory "D:\http\a">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
<VirtualHost site-b.com:443>
DocumentRoot "D:\http\b"
ServerName site-b.com
SSLEngine On
SSLCertificateFile "C:/xampp/apache/conf/ssl.crt/server.crt"
SSLCertificateKeyFile "C:/xampp/apache/conf/ssl.key/server.key"
<Directory "D:\http\b">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment