How do I find user timezone in php? - php

How can I dynamically find user timezone in config.php file in codeigniter?
date_default_timezone_set('Asia/Kolkata');

You must either use javascript (for example http://momentjs.com/timezone/) or then you must use the geoip to determine it in the backend side (CURL the client ip to http://freegeoip.net/?q=IP_ADDR). Also if you have multiple TLDs (for example .com, .se etc.) you can use those if nothing else works. Of course you should allow the user to change the timezone from user interface in case the automatic way fails for some reason.

Using Javascript you can get the user timezone:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
document.getElementById("hiddenVal").value = timezone;
</script>
After getting timezone in javascript you can use that value in php code.
In HTML make an hidden element with name and id as "hiddenval" and get value from that element on form submit like
<?hpp
echo$usertime_zone = $_REQUEST['hiddenval'];
?>
In case if you only want to use PHP then utilize the following code:
<?php
$ip = $_SERVER['REMOTE_ADDR']; // means we got user's IP address
$json = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);
if ($ipData['timezone']) {
$tz = new DateTimeZone( $ipData['timezone']);
$now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
// we can't determine a timezone - do something else...
}

<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head> section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head> section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://domain.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

Related

How to convert server time to local time in Laravel?

I would like to print the time in local time in Laravel. If the user create a post it will display the created time on the server. How can I display it in local time ?
In my blade file I used this code to display created time,
{{{ $posts->updated_at }}}
Which displays the time in database, which is a server time. How can I convert it to users local time ?
I found a solution to convert time to local time by using session. The current time zone offset will store on session to calculate users time. Create a jquery post function to post users timezone offset to session. This is my code,
default.blade.php
#if($current_time_zone=Session::get('current_time_zone'))#endif
<input type="hidden" id="hd_current_time_zone" value="{{{$current_time_zone}}}">
// For assigning session value to hidden field.
<script type="text/javascript">
$(document).ready(function(){
if($('#hd_current_time_zone').val() ==""){ // Check for hidden field is empty. if is it empty only execute the post function
var current_date = new Date();
curent_zone = -current_date.getTimezoneOffset() * 60;
var token = "{{csrf_token()}}";
$.ajax({
method: "POST",
url: "{{URL::to('ajax/set_current_time_zone/')}}",
data: { '_token':token, curent_zone: curent_zone }
}).done(function( data ){
});
}
});
routes.php
Route::post('ajax/set_current_time_zone', array('as' => 'ajaxsetcurrenttimezone','uses' => 'HomeController#setCurrentTimeZone'));
HomeController.php
public function setCurrentTimeZone(){ //To set the current timezone offset in session
$input = Input::all();
if(!empty($input)){
$current_time_zone = Input::get('curent_zone');
Session::put('current_time_zone', $current_time_zone);
}
}
Helpers/helper.php
function niceShort($attr) {
if(Session::has('current_time_zone')){
$current_time_zone = Session::get('current_time_zone');
$utc = strtotime($attr)-date('Z'); // Convert the time zone to GMT 0. If the server time is what ever no problem.
$attr = $utc+$current_time_zone; // Convert the time to local time
$attr = date("Y-m-d H:i:s", $attr);
}
return attr;
}
index.blade.php
{{ niceShort($posts->updated_at) }}
Now we can print the time in clients time zone. The time zone setting code run only when the session empty.
You can do this by using javascript. Use following libraries:
moment.min.js (http://momentjs.com/downloads/moment.js)
moment-timezone-with-data.js ()
jstz.min.js (https://bitbucket.org/pellepim/jstimezonedetect)
Here is the code :
var update_at = '<?php echo $posts->updated_at;?>'; //set js variable for updated_at
var serverTimezone = 'YOUR SERVER TIME ZONE'; //set js variable for server timezone
var momentJsTimeObj = moment.tz(update_at, serverTimezone); //create moment js time object for server time
var localTimeZone = jstz.determine(); //this will fetch user's timezone
var localTime = momentJsTimeObj.clone().tz(localTimeZone.name()).format(); //convert server time to local time of user
Now you can display local time through js
Try this method, I think this is what you want:
$localTime = $object->created_at->timezone($this->auth->user()->timezone);
Here, $this->auth->user()->timezone will return current user's timezone, and timezone() will convert created_at to to user's local time.
If you want to get all visitors timezone (not just logged in users), you can you package for Laravel similar to laravel-geoip. It will generate $visitor['timezone'] for you which you can use like this:
$localTime = $object->created_at->timezone($visitor['timezone']);
Best option is to do this with Javascript, get client's timezone and then convert server time to cleint's accordingly.
Please refer https://stackoverflow.com/a/1837243/4007628
Try this:
$dt = new DateTime($posts->updated_at);
$tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after
$dt->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s');
Go to app.php page in Config folder and change this
'timezone' => 'UTC',
to
'timezone' => 'addYourTimeZoneHere',
reference
https://laravel.com/docs/5.5/configuration
find your timezone
http://php.net/manual/en/timezones.php
Server time should stick with UTC timezone
In front end, you can use moment.js to render the correct local timezone. I tested this in moment version 2.22.2.
Simply add Z to the datetime value and moment will render the date to user's local time zone
moment(dateTimeValue + ' Z');
Comment the timezone settings in app.php page
//'timezone' => 'UTC',

jquery countdown changes when user change its system time

i'm using jquery countdown with php. i have given an end date which is going to the countdown. my problem is lets suppose 1 hour left is showing in countdown but when a user change its system time the countdown changes. like if a user back his time 1 hour then the counter will display the 2 hours left. is there any way to get the server time for more accurate time not the user system time. please help.
how can i get server time not user system time?
below is my jquery code
if($(pluginsArray[6]).length){
$(pluginsArray[6]).each(function(){
var $this = $(this),
dateObj = $this.data();
var finalDate = new Date(dateObj.year, dateObj.month, dateObj.day, dateObj.hours, dateObj.minutes);
$this.countdown({
timezone: +4,
until : finalDate,
expiryText: '<div class="over">Closed.</div>',
onExpiry : function(){
setTimeout(function( ) { location.reload(); }, 5000);
},
format :'DHMS',
layout : '<b>{dn}</b> <span class="fs_medium d_inline_b m_right_5">days</span> <b>{hn}</b> <span class="fs_medium d_inline_b m_right_5">hrs</span> <b>{mn}</b> <span class="fs_medium d_inline_b m_right_5">min</span> <b>{sn}</b> <span class="fs_medium">sec</span>'
});
});
}
and here is what i did in php
<div class="countdown color_redc d_inline_m fs_large second_font lh_small f_xs_20" style="font-size:26px;" data-year="<?= $aDate[0] ?>" data-month="<?= ($aDate[1] - 1) ?>" data-day="<?= $aDate[2] ?>" data-hours="<?= $aDate[3] ?>" data-minutes="<?= $aDate[4] ?>"></div>
Solution without PHP
What you can do, without coding any server side is using a public API to get current time.
Found a similar topic on StackoverFlow : Free Rest API to get current time as string (timezone irrelevant)
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for
a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
GenoNames looks to be US only, TimezoneDb works you just need to register for a free public key.
Few people recommend timeapi.org but looks like they do not accept CROSS-DOMAIN request in Ajax, and the exemple they provide is no longer available.
Solution with PHP and jQuery Countdown configuration
Also you can ask jQuery CountDown to synchronyze with your server using serverSync option
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
PHP file : serverTime.php
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
BUT
Keep in mind your user will always be able to change your code and fake it ... so if you need to implement some security this is not enough and you will need to code some backend stuff.

Php date function in javascript

In this i am posting a question in which i am using a java script and PHP code and sending back the timestamp using the time function of the PHP. let have the code,
<?php
session_start();
echo time();
?>
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(this).mousemove(function(){
var time_=new Date();
var time=<?php echo time();?>;
alert(time);
$.post('loggout.php',{input: time});
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
now the problem is that when i move the mouse than the mousemove event gets into action and displays the value of the var time. but every time it displays the same value. the value only changes when i reload the page. so please let me know the reason behind it and how to make this dynamic
This is because the PHP is only run once - when the page loads. So the Javascript time variable gets filled with the time returned by PHP and then never changes.
If you're happy to get the client-side time, just use this:
var time = time.getTime();
Instead of var time=<?php echo time();?>;
Otherwise, you can use AJAX to send a query that'll run some PHP, return the time, and put it into the variable.
For example, you could try something like this:
$.get('getTime.php', function(data) {
time = data;
});
And in getTime.php, just echo the time.
This is because PHP is back-end programing language and once your page loaded timestamp written to code and can't be dynamic. But you can send JS timestamp:
var time = Math.round(+new Date() / 1000);
( + will convert date Object to integer )
or
var time = Math.round(new Date().getTime() / 1000);
division by 1000 needed because JS use milliseconds.
See Date reference at MDN.
put this javascript code anywhere in your php file.
<script type="text/javascript">
var currenttime = '<?php echo date("F d, Y H:i:s"); ?>' //PHP method of getting server date
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var serverdate=new Date(currenttime)
function padlength(what){
var output=(what.toString().length==1)? "0"+what : what
return output
}
function displaytime(){
serverdate.setSeconds(serverdate.getSeconds()+1)
var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
document.getElementById("servertime").innerHTML=timestring
}
window.onload=function(){
setInterval("displaytime()", 1000);
}
</script>
add span or div where you want to show current time. no need to reload page.
<span id="servertime"></span>

JavaScript / PHP: Get a Client's Month and Day with JS, Pass the Values to PHP Variable

I want to get day and month from a client's computer, and then pass it to PHP in two separate variables, which would result in something like this:
$day_num = 11;
$month_num = 12;
I need JavaScript function and PHP function to be separate files, and I need to pass the value
not in the URL.
I would be grateful for a bit of help from an expert!
Javascript:
If you are using jQuery gettting it back to the server is super easy (if you do it without, see: How to make an AJAX call without jQuery?):
<script language="javascript">
var date = new Date(),
month = date.getMonth(),
day = date.getDate();
$.post('path-to-php.php', { day: day, month: month});
</script>
PHP:
<?php
var_dump($_POST['day']);
var_dump($_POST['month']);
?>
Edit:
path-to-php.php is the filename of your php file. It can be absolute or relative, depending on your application. If you wanted to post it to the same file, you could use this instead of path-to-php.php: <?php echo $_SERVER['PHP_SELF'];?>
With javascript:
function executeAjax() {
var date = new Date(),
var month = date.getMonth(),
var day = date.getDate();
var url="daymonth.php?month="+month+"&day="+day;
var objX=new XMLHttpRequest();
objX.open("GET",url,false);
objX.send(null);
var response=objX.responseText;
}
daymonth.php
<?php
$day=$_GET['day'];
$month=$_GET['month'];
?>

JQuery and PHP Date difference

I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>
jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');
DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client

Categories