Skip to content

Bug: CodeIgniter doesn't set the timezone in database sessions #9903

Closed

Description

@LenoilR

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

  1. Create a MySQL table with a column whose value is a time and whose default value is current_timestamp().
  2. Insert a new record in the table using query builder's or model's insert method, not supplying a value for the column. Retrieve that value and display it alongside the output of Time::now();
  3. change $appTimezone in App\Config\App.php to a different timezone string and rerun the test code.
  4. 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:

  1. Create file App\Database\Connection.php and create a new Connection class that extends CodeIgniter\Database\MySQLi\Connection.
  2. 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);
    }

  1. 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

  1. added
    bug
    on Jan 30, 2026
  2. miladjef commented on Feb 2, 2026

    @miladjef

    Modified Connection.php for MySQLi Driver

    '<?php

    declare(strict_types=1);

    /**

    • This file is part of CodeIgniter 4 framework.
    • (c) CodeIgniter Foundation admin@codeigniter.com
    • For the full copyright and license information, please view
    • the LICENSE file that was distributed with this source code.
      */

    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
      {
      /
      *

      • Database driver
      • @var string
        */
        public string $DBDriver = 'MySQLi';

      /**

      • DELETE hack flag
      • Whether to use the MySQL "delete hack" which allows the number
      • of affected rows to be shown. Uses a preg_replace when enabled,
      • adding a bit more processing to all queries.
      • @var bool
        */
        public bool $deleteHack = true;

      /**

      • Identifier escape character
      • @var string
        */
        public string $escapeChar = '`';

      /**

      • MySQLi object
      • Has to be preserved without being assigned to $conn_id.
      • @var mysqli|null
        */
        protected ?mysqli $mysqli = null;

      /**

      • Whether to synchronize database session timezone with PHP timezone
      • @var bool
        */
        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 = [];

         if (! empty($this->encrypt['ssl_key'])) {
             $ssl['key'] = $this->encrypt['ssl_key'];
         }
        
         if (! empty($this->encrypt['ssl_cert'])) {
             $ssl['cert'] = $this->encrypt['ssl_cert'];
         }
        
         if (! empty($this->encrypt['ssl_ca'])) {
             $ssl['ca'] = $this->encrypt['ssl_ca'];
         }
        
         if (! empty($this->encrypt['ssl_capath'])) {
             $ssl['capath'] = $this->encrypt['ssl_capath'];
         }
        
         if (! empty($this->encrypt['ssl_cipher'])) {
             $ssl['cipher'] = $this->encrypt['ssl_cipher'];
         }
        
         if ($ssl !== []) {
             $this->mysqli->ssl_set(
                 $ssl['key'] ?? null,
                 $ssl['cert'] ?? null,
                 $ssl['ca'] ?? null,
                 $ssl['capath'] ?? null,
                 $ssl['cipher'] ?? null
             );
        
             $clientFlags |= MYSQLI_CLIENT_SSL;
        
             // Require verification of SSL certificate
             if (
                 isset($this->encrypt['ssl_verify'])
                 && $this->encrypt['ssl_verify'] === true
             ) {
                 $clientFlags |= MYSQLI_CLIENT_SSL_VERIFY_SERVER_CERT;
             }
         }
        

        }

        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!';

                 throw new DatabaseException($message);
             }
        
             if (! $this->mysqli->set_charset($this->charset)) {
                 throw new DatabaseException(sprintf(
                     'Unable to set the configured connection charset ("%s").',
                     $this->charset
                 ));
             }
        
             return $this->mysqli;
         }
        

        } 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

      • {

      • $vars = parent::buildSessionVars();
        
      • $vars['wait_timeout'] = '28800';
        
      • $vars['max_execution_time'] = '30000';
        
      • return $vars;
        
      • }
        */
        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]
      }'

  3. michalsn commented on Feb 6, 2026

    @michalsn
    Member

    This feature will be included in the 4.8 release.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions