Find the time-zone & local time of your website visitors with PHP

ipapi ~ ipapi.co
1 min readSep 7, 2023

--

Continuing our series where we had discussed why it’s helpful to show the content on your website or app based on the user’s local time. Here, we will use PHP to find the time zone (using the API) and use it to compute the local time.

<php

// API endpoint
$ipAddress = "8.8.8.8";
$apiUrl = "https://ipapi.co/".$ipAddress."/json/";

// Fetch the data from the API
$response = file_get_contents($apiUrl);

// Check if the request was successful
if ($response !== false) {
// Decode the JSON data
$data = json_decode($response, true);

// Check if the 'timezone' key exists in the decoded data
if (isset($data['timezone'])) {
$visitorTimezone = $data['timezone'];

// Output the timezone
echo "Visitor's Timezone: $visitorTimezone<br>";

// Calculate and output the local time of the visitor
$dateTime = new DateTime('now', new DateTimeZone($visitorTimezone));
echo "Visitor's Local Time: " . $dateTime->format('Y-m-d H:i:s');
} else {
echo $response;
}
} else {
echo "Error accessing the API.";
}

?>

For any help / support, please don’t hesitate to contact us.

--

--

ipapi ~ ipapi.co
ipapi ~ ipapi.co

Written by ipapi ~ ipapi.co

IP Lookup | IP Geolocation API | IP Address Locator by Kloudend, Inc. USA. Trusted by Fortune 500 !

No responses yet