How to change php timezone on your server

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to change php timezone on your server

Normally when using a shared hosting service, the server you are being hosted on has a different timezone set. So your scripts may be displaying a different time than what you expect. Fixing this is not hard at all, however some users think that the server timezone needs to be changed entirely for their script to work, which is not correct. Think of it this way, what if there’s another client that requires a different timezone than the one you are one? What then?

PHP developers need to know of a few functions they can use, server administrators need to know of a few .htaccess rules they can advise. Basically there are two set of solutions, based on PHP and based on .htaccess.

For both solution the end user has direct access and can change them however he needs.

Change timezone from php

When using php, the timezone can be changed using the function date_default_timezone_set() with a list of timezone from:

An example of how you can set this is bellow:

Timezone for your entire script will be set to Europe/London and you can then use the script as normal.

There are different ways to change a specific date into a different timezone also, you can use strftime() and strtotime() functions for this:

Of course, this will only work if you know your current timezone and the hour difference so that you can adjust it as you need.

Some shared hosting providers which uses suPHP as php handler now allow you to create a php.ini file inside your document root. Using this php.ini you can alter server settings only for your document root  / domain. So if you know you can do this, you can add to your php.ini file the following:

Do keep in mind however, this php.ini file will not recursively set your php  environment, it will only work in the exact folder where the php.ini file was created.

Change timezone using .htaccess

Server administrators usually would know that its possible to change the timezone using .htaccess, of course the web server need to allow making these changes, but on shared hosting you normally are allowed to do this.

An example of what you need to add to the top of your .htaccess file is:

And you are done. You can then check your scripts, they should have the proper timezone settings set.

What I do recommend however is using the first method, the date_default_timezone_set() function, as it gives you proper control thought your entire script.

That’s it for now, see you again in our next tutorial.

Request an article ←