Repository navigation
Description
PHP Version
8.2
CodeIgniter4 Version
4.4.6 (but current version has same issue)
CodeIgniter4 Installation Method
Composer (using codeigniter4/appstarter)
Which operating systems have you tested for this bug?
Windows, Linux
Which server did you use?
apache
Environment
production, development
Database
MariaDB 10.6
What happened?
CodeIgniter sets the timezone in PHP based on the setting of the variable $appTimezone in App\Config\App.php. It doesn't, however, set the timezone for database sessions. The result of this, if the database server is in a different timezone than the one set in $appTimezone, is that database functions like NOW() will return incorrect times.
Steps to Reproduce
- Create a MySQL table with a column whose value is a time and whose default value is current_timestamp().
- Insert a new record in the table using query builder's or model's
insertmethod, not supplying a value for the column. Retrieve that value and display it alongside the output of Time::now(); - change $appTimezone in App\Config\App.php to a different timezone string and rerun the test code.
- The times will vary by however many hours difference there is between the $appTimezone setting and whatever the global timezone setting is on the database server.
Expected Output
The time displayed by Time::now() in CodeIgniter and the time added to a record in the database by a default value of current_timestamp() should be the same.
Anything else?
The only way to fix this is in the connect method of the database driver. For the MySQLi driver, this would entail including "SET SESSION time_zone=offset" in the call to mysqli->options(MYSQLI_INIT_COMMAND...), where offset is the time offset of the time zone in $appTimezone from UTC in the format +|-HH:MM.
I've successfully modified the code to do this, by adding a setSessionVars method to CodeIgniter\Database\MySQLi\Connection:
public function setSessionVars(array $sessionVars) : void {
$initString = '';
foreach ($sessionVars as $var => $value) {
$initString .= (!$initString? 'SET' : ',') . ' SESSION ' . $var . '=' . $value;
}
$this->mysqli->options( MYSQLI_INIT_COMMAND, $initString );
}
I then modified these lines in the connect method:
if ($this->strictOn !== null) {
if ($this->strictOn) {
$this->mysqli->options(
MYSQLI_INIT_COMMAND,
"SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')",
);
} else {
$this->mysqli->options(
MYSQLI_INIT_COMMAND,
"SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
@@sql_mode,
'STRICT_ALL_TABLES,', ''),
',STRICT_ALL_TABLES', ''),
'STRICT_ALL_TABLES', ''),
'STRICT_TRANS_TABLES,', ''),
',STRICT_TRANS_TABLES', ''),
'STRICT_TRANS_TABLES', '')",
);
}
}
to this:
$tzoffset = Time::now()->getOffset(); // seconds from GMT
$tzoffset = sprintf("%+03d:%02d", floor($tzoffset/3600), abs(($tzoffset%3600)/60)); // +|-HH:MM
$sessionVars = ['time_zone' => "'".$tzoffset."'" ];
if (isset($this->strictOn)) {
$sessionVars['sql_mode'] = ($this->strictOn)?
"CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')"
: "REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
@@sql_mode,
'STRICT_ALL_TABLES,', ''),
',STRICT_ALL_TABLES', ''),
'STRICT_ALL_TABLES', ''),
'STRICT_TRANS_TABLES,', ''),
',STRICT_TRANS_TABLES', ''),
'STRICT_TRANS_TABLES', '')"
;
}
$this->setSessionVars( $sessionVars );
Adding the setSessionVars method would allow users to easily set additional session variables by doing the following:
- Create file App\Database\Connection.php and create a new Connection class that extends CodeIgniter\Database\MySQLi\Connection.
- Override the setSessionVars method to add the additional variables and their values to the $sessionVars array and then call the parent method:
public function setSessionVars(array $sessionVars) : void {
// set the foo session variable to value 'bar'
$sessionVars['foo'] = "'bar'";
parent::setSessionVars($sessionVars);
}
- Tell CodeIgniter to use your new class by changing the DBDriver entry in the $default array in App\Config\Database.php from 'MySQLi' to 'App\Database'.
Activity
miladjef commentedon Feb 2, 2026
Modified Connection.php for MySQLi Driver
'<?php
declare(strict_types=1);
/**
*/
namespace CodeIgniter\Database\MySQLi;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\I18n\Time;
use mysqli;
use mysqli_result;
use mysqli_sql_exception;
use stdClass;
use Throwable;
/**
Connection for MySQLi
@extends BaseConnection<mysqli, mysqli_result>
/
class Connection extends BaseConnection
{
/*
*/
public string $DBDriver = 'MySQLi';
/**
*/
public bool $deleteHack = true;
/**
*/
public string $escapeChar = '`';
/**
*/
protected ?mysqli $mysqli = null;
/**
*/
public bool $DBTimezoneSync = true;
/**
Connect to the database.
@return mixed
@throws DatabaseException
*/
public function connect(bool $persistent = false)
{
// Do we have a socket path?
if ($this->hostname[0] === '/') {
$hostname = null;
$socket = $this->hostname;
} else {
$hostname = ($persistent === true) ? 'p:' . $this->hostname : $this->hostname;
$socket = '';
}
$clientFlags = $this->compress === true ? MYSQLI_CLIENT_COMPRESS : 0;
$this->mysqli = mysqli_init();
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
$this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
if (isset($this->strictOn)) {
if ($this->strictOn) {
$this->mysqli->options(
MYSQLI_INIT_COMMAND,
"SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')"
);
} else {
$this->mysqli->options(
MYSQLI_INIT_COMMAND,
"SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
@@sql_mode,
'STRICT_ALL_TABLES,', ''),
',STRICT_ALL_TABLES', ''),
'STRICT_ALL_TABLES', ''),
'STRICT_TRANS_TABLES,', ''),
',STRICT_TRANS_TABLES', ''),
'STRICT_TRANS_TABLES', '')"
);
}
}
// Set session variables including timezone synchronization
$this->setSessionVars($this->buildSessionVars());
if (is_array($this->encrypt)) {
$ssl = [];
}
try {
if ($this->mysqli->real_connect(
$hostname,
$this->username,
$this->password,
$this->database,
(int) $this->port,
$socket,
$clientFlags
)) {
// Prior to version 5.7.3, MySQL silently downgrades to an unencrypted
// connection if SSL setup fails
if (
($clientFlags & MYSQLI_CLIENT_SSL)
&& version_compare($this->mysqli->client_info, '5.7.3', '<')
&& empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)
) {
$this->mysqli->close();
$message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!';
} catch (mysqli_sql_exception $e) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
return false;
}
/**
Build session variables array for MySQL connection
@return array<string, string>
*/
protected function buildSessionVars(): array
{
$sessionVars = [];
// Synchronize database timezone with PHP timezone
if ($this->DBTimezoneSync) {
$sessionVars['time_zone'] = "'" . $this->getTimezoneOffset() . "'";
}
return $sessionVars;
}
/**
Get the current PHP timezone offset in MySQL format (+HH:MM or -HH:MM)
@return string Timezone offset in format +/-HH:MM
*/
protected function getTimezoneOffset(): string
{
$offset = Time::now()->getOffset(); // offset in seconds from UTC
$hours = (int) floor(abs($offset) / 3600);
$minutes = (int) ((abs($offset) % 3600) / 60);
$sign = $offset >= 0 ? '+' : '-';
return sprintf('%s%02d:%02d', $sign, $hours, $minutes);
}
/**
Set MySQL session variables during connection initialization
This method can be overridden in child classes to add custom session variables.
Variables are set using MYSQLI_INIT_COMMAND which executes them immediately
after connection is established.
@PARAM array<string, string> $sessionVars Associative array of variable => value pairs
@return void
@example
// In your custom Connection class:
protected function buildSessionVars(): array
{
}
*/
public function setSessionVars(array $sessionVars): void
{
if ($sessionVars === []) {
return;
}
$statements = [];
foreach ($sessionVars as $variable => $value) {
$statements[] = 'SESSION ' . $variable . ' = ' . $value;
}
$initCommand = 'SET ' . implode(', ', $statements);
$this->mysqli->options(MYSQLI_INIT_COMMAND, $initCommand);
}
// ... [rest of the existing methods remain unchanged]
}'
michalsn commentedon Feb 6, 2026
This feature will be included in the
4.8release.