Set Timezone in PHP By Editing php.ini File

Do you want to set or change a timezone in PHP? PHP runs on a server that has its own timezone. The date and time work in your PHP application as per this timezone. In this article, we discuss how one can set a timezone in PHP using the php.ini file.

What is PHP.INI File?

The php.ini is a configuration file required to run PHP applications. Whenever a web server(apache/nginx) is started, the system reads this config file. This file contains settings for displaying log errors, uploading maximum size, file timeouts, timezone, and much more.

Note: You must restart the server when you change settings in the php.ini file.

The location of the php.ini file differs depending on the server you are using. In the case of XAMPP, the location is at xampp/php/php.ini. If you are not aware of file location then you can get it by simply calling the phpinfo() method as follows.

<?php
phpinfo();

Add this statement in any PHP file, run it on the browser, find php.ini and you will get its path. Don’t forget to delete this file or statement as it exposes your server configuration to the world.

Why Need to Change Timezone?

There are several reasons why you might need to change the default timezone. You are building a website and you probably want to keep the date and time of the application in your timezone. Your server may have set a different timezone which creates confusion for you.

If your website is working globally and you need to deal with different timezones then read our article How to Handle Timezones in PHP.

Set Default Timezone in php.ini

Open your php.ini file in the editor and search for the string ‘timezone’. You will find the statement something like below.

date.timezone=Asia/Kolkata
set-timezone-in-php

Here, you can set the timezone you wish to apply for your website. Get the list of supported timezones from this link.

For instance, I need to set my timezone to ‘Chicago’. The string for this timezone is ‘America/Chicago’ so I will add the below statement to the php.ini file.

date.timezone=America/Chicago

After this, we need to restart the server to take effect of the new changes. On the Ubuntu system, you can restart the server using the command:

sudo systemctl restart apache2

It may happen that you’re not able to get or edit your server’s php.ini file. In such cases, you can create a new blank php.ini file in your project root directory and add the desired statement(s) to it. However, it’s not a guarantee this approach would work. You can give it a try if you don’t have access to the main configuration file.

I hope you understand how to set a timezone in PHP. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “Set Timezone in PHP By Editing php.ini File

Leave a Reply

Your email address will not be published. Required fields are marked *