0

I would like to print on the screen on a PHP page, the date of the last update. Searching online I tried to create a code, however the result appears in English and not in the visitor's local language.

<?php
setlocale(LC_TIME,"it_IT");
echo "Ultimo aggiornamento" . date ("g:ia \o\n l jS F Y", getlastmod());
?>

Could you please give me a hand?

  • 1
    do you want to display the date:time in the visitors timezone, or you want the user to get the message in his/her own language, or both? – Random Dude May 07 '20 at 17:47
  • Hi @David Hlavati! Thank you for the clarification. I would like the user to receive the message in his language. For example, I am Italian and I would like the months and days to appear in Italian and so on. – Gabriele C. May 07 '20 at 18:34

1 Answers1

1

This task has two parts.

First one is to solve the localization issue. For this you can create language files, like it.php, en.php, ect. and in the files you would an array, which contains the translation.

for example: en.php

return [
    'lastUpdate' => 'Last update',
    'dateTimeFormat' => 'Y-m-d H:i:s'
];

then it.php

return [
    'lastUpdate' => 'Ultimo aggiornamento',
    'dateTimeFormat' => 'g:ia \o\n l jS F Y'
];

and other language files in the same way.

You can also use google translate API and a php script to generate these files if there are way too many languages and texts that you would like support on the site, but then the translation quality is up to the google translate level, which is not so perfect.

Then once you detect/guess the user's language, you can select the language file, and use it for the texts on the page:

$lang = __DIR__ . "{$userLang}.php";
echo "{$lang['lastUpdate']} " . date ($lang['dateTimeFormat'], getlastmod());

The other part of the story is the language detection.

With the php you can get the user's IP address, and then you can use a table which contains which IPv4 ranges belongs to which country. But there is a problem with this. It's possible that the user is using tor browser, proxy, masking the IP address. Living in a different country then his/her homeland, or just traveled to that country. So in these cases the guessing will be incorrect.

A better way to do this is to check the user's browser or system language with javascript on the front-end side. But it can still make mistakes, since maybe the user is in a different country with a borrowed PC where the OS and browser language is different.

So it's also good if you provide a way for the user on the page to select his/her language and then store it in a cookie.

Random Dude
  • 872
  • 1
  • 9
  • 24