0

//Solved I used ip-api.com's json, working fine.

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$ipInfo = file_get_contents('http://ip-api.com/json/'.$ip);
$ipInfo = json_decode($ipInfo);
$timezone = $ipInfo->timezone;
date_default_timezone_set($timezone);
echo date('d F Y, h:i:s A');
?>

//old question

Peace be upon you. Actually I want user's timezone using PHP. My current code is this

<?php
$timezone = 'Asia/Karachi'; /*BUT REQUIRMENT IS DIFF FOR DIFF AREA*/
date_default_timezone_set($timezone);
echo date('d F Y, h:i:s A');
?>

I tried this but not working

<?php
 
function dp_get_timezone($latitude,$longitude,$username) {
        //error checking
        if (!is_numeric($latitude)) { return 'invalid latitude'; }
        if (!is_numeric($longitude)) { return 'invalide longitude'; }
        if (!$username) { return 'invalid username'; }
 
        //connect to web service
        $url = 'http://api.geonames.org/timezone?lat='.$latitude.'&lng='.$longitude.'&style=full&username='.urlencode($username);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $xml = curl_exec($ch);
        curl_close($ch);
        if (!$xml) { $GLOBALS['error'] = 'No data: '.$url; return false; }
 
        //parse XML response
        $data = new SimpleXMLElement($xml);
        // echo '<pre>'.print_r($data,true).'</pre>'; die();
        $timezone = trim(strip_tags($data->timezone->timezoneId));
        if ($timezone) { return $timezone; }
        else { $GLOBALS['error'] = 'No timezone: '.$url; return false; }
}
 
?>

then modified my current code

<?php
$timezone = dp_get_timezone($map['lat'],$map['lng'],'username'); 
date_default_timezone_set($timezone);
echo date('d F Y, h:i:s A');
?>

NOTE: IF MY QUESTION IS TOO LONG IT'S JUST BECAUSE OF LENGTHY CODE

Ahmed Raza
  • 39
  • 4
  • 1
    What about it isn't working? Are you getting an error message anywhere? – aynber Feb 28 '22 at 16:53
  • @aynber yes it's showing ```DateTimeZone->__construct('invalid latitud...')``` – Ahmed Raza Feb 28 '22 at 17:50
  • You always assume that `dp_get_timezone` is returning a valid response. Make sure that `$timezone` is what you think it is before you attempt to set the timezone. `$map['lat']` is apparently not numeric, so you'll need to find out why as well – aynber Feb 28 '22 at 17:53

0 Answers0