Prerequisites
- Access to root user or a user with sudo privileges.
- Installed PHP (any version) on CentOS 7.
Step 1: Determine the Current Timezone
First, determine the current PHP timezone setting. You can do this by creating a simple PHP script:
<?php
echo date_default_timezone_get();
?>
Save this script to a file and run it in a browser or from the command line. It will display the current timezone setting.
Step 2: Set the Timezone in PHP.ini
PHP.ini is the main configuration file for PHP. To change the timezone, locate and edit this file.
- Open the php.ini file using a text editor. The path to the file might be, for example,
/etc/php.ini
:sudo nano /etc/php.ini
- Find the line
;date.timezone =
and change it to reflect your desired timezone. For example:date.timezone = "Europe/Prague"
Remember to remove the semicolon at the beginning of the line, which uncomments this directive.
-
Save and close the file.
-
Step 3: Restart the Web Server
-
After editing the configuration file, you need to restart the web server for the changes to take effect. If you're using Apache, restart it with:
sudo systemctl restart httpd
For Nginx, use:
sudo systemctl restart nginx
-
Step 4: Verify the Timezone Setting
To verify that the timezone has been set correctly, create or modify the previous PHP script:
<?php echo date_default_timezone_get(); ?>
Run this script again. It should now display the newly set timezone.
Additional Steps
- For dynamic applications where the timezone may need to be changed based on user preferences, you can use the
date_default_timezone_set()
function directly in your code. - Remember to test your applications after changing the timezone to ensure everything is functioning as expected.
Setting the correct timezone in PHP on CentOS 7 is an important step to ensure your web applications handle dates and times properly. Follow the steps outlined above to ensure your applications process data and time accurately.