Skip to content

Instantly share code, notes, and snippets.

@nlehuen
Created May 11, 2012 21:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nlehuen/2662513 to your computer and use it in GitHub Desktop.
Save nlehuen/2662513 to your computer and use it in GitHub Desktop.
This script prepares the PHP session.save_path directory for spreading session files on multiple levels. It is a replacement for the infamous mod_files.sh script.
#!/usr/bin/php
<?php
// See http://www.php.net/manual/en/session.configuration.php#ini.session.save-path
function prepare_dir($base, $hash_chars, $depth, $number) {
if($depth<0) return $number;
if(!file_exists($base)) {
mkdir($base, 0777);
echo "$base\n";
$number++;
}
for($i=0,$l=strlen($hash_chars);$i<$l;$i++) {
$dir = $base . DIRECTORY_SEPARATOR . $hash_chars[$i];
$number = prepare_dir($dir, $hash_chars, $depth - 1, $number);
}
return $number;
}
function move_sessions($session_folder, $current, $hash_chars, $depth, $number) {
$dir = dir($current);
while(($file = $dir->read()) !== false) {
if($file === '.' || $file === '..') continue;
$full_name = $current . DIRECTORY_SEPARATOR . $file;
if(is_dir($full_name)) {
$number = move_sessions($session_folder, $full_name, $hash_chars, $depth, $number);
} else if(preg_match("/^sess_[$hash_chars]+$/", $file)) {
$new_name = $session_folder;
for($i=0;$i<$depth;$i++) {
$new_name .= DIRECTORY_SEPARATOR . $file[5 + $i];
}
$new_name .= DIRECTORY_SEPARATOR . $file;
if($full_name !== $new_name) {
echo "$full_name > $new_name\n";
rename($full_name, $new_name);
$number++;
}
}
}
$dir->close();
return $number;
}
function main() {
$save_path = ini_get('session.save_path');
if(preg_match('/^(\d)+;(.+)$/', $save_path, $result)) {
$depth = $result[1];
$session_folder = $result[2];
echo "Base session folder : $session_folder\n";
echo "Session folder depth : $depth\n";
$hash_bits = ini_get('session.hash_bits_per_character');
echo "Hash bits : $hash_bits\n";
$hash_chars = '0123456789abcdef';
if($hash_bits >= 5) {
$hash_chars .= 'ghijklmnopqrstuv';
if($hash_bits >= 6) {
$hash_chars .= 'wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
}
}
$number = prepare_dir($session_folder, $hash_chars, $depth, 0);
echo "Created $number folders.\n";
echo "Moving sessions in the right place...\n";
$number = move_sessions($session_folder, $session_folder, $hash_chars, $depth, 0);
echo "Moved $number session files\n";
} else {
echo "Session folder : $save_path\n";
echo "No depth, no need to do anything\n";
}
}
main();
@arnisjuraga
Copy link

Great boilerplate!
I updated a little bit for my needs and php7.2 (hash_bits_per_character is removed, so I just set $hash_bits to 5 for now).
Will move 6m session files and then we'll see if it's needed to be increased.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment