If you are using symfony, you can use a command like this:
yml configuration:
parameters:
redis_address: "localhost"
project_name : "ACME_"
snc_redis:
clients:
default:
type: predis
alias: default
dsn: redis://%redis_address%
logging: '%kernel.debug%'
session:
type: predis
alias: session
dsn: redis://%redis_address%/1
logging: true
session:
client: session
prefix: '%project_name%PHPREDIS_SESSION'
ttl: 7776000 # 90 days
symfony command:
<?php
// Command: app/console acme:migrate:session:files:to:redis --env=dev
namespace Acme\AppBundle\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Finder\Finder;
class MigrateSessionFilesToRedisCommand extends ContainerAwareCommand {
protected $env;
protected function configure() {
$this->setName('acme:migrate:session:files:to:redis')
->setDescription("Migrate Session Files To Redis")
->setHelp("Migrate Session Files To Redis");
}
protected function execute(InputInterface $input, OutputInterface $output) {
$sessionPath = realpath( sprintf('%s%s', $this->getContainer()->getParameter('kernel.root_dir'), '/sessions') );
$prefix = 'ACME_PHPREDIS_SESSION';
$redis = $this->getContainer()->get('snc_redis.session');
$finder = new Finder();
$finder->files()->in($sessionPath);
foreach ($finder as $file) {
$realPath = $file->getRealpath();
$sessionId = str_replace( 'sess_', '', $file->getRelativePathname() );
$redis->append( sprintf('%s:%s', $prefix, $sessionId) , file_get_contents( $realPath ) );
}
}
}
Note: Replace "ACME" with your Project ID/Name and Set The right Session Path where files are stored.
$redis->set("PHPREDIS_SESSION:".session_id(), session_encode());right before each script ends. (this may add a little bit of overhead depending on the amount of data in session and how session_encode works)