Thursday, April 07, 2005

PHP: get_user_time_js()

Finally put together a function that uses javascript to grab the time offset from a user's browser and feed that back to the php script. Still need to add some conditional handling for browsers with javascript turned off.

/* Fx get_user_time_js()
author:tatwell AT gmail DOT com
******************************/
function get_user_time_js($add_clear_button=FALSE) {

// handle reset button
if ( isset($_POST['reset_tz']) ) {
$_SESSION['got_tz'] = '';
$_SESSION['user_tz'] = '';
}

// avoid infinite loops
if ( empty($_SESSION['got_tz']) ) {
$_SESSION['got_tz'] = FALSE;
}

// JAVASCRIPT PART
// if tz already determined, don't post
if ( isset($_POST['tz']) ) {
$hr_offset = $_POST['tz'] / 60; /* convert from minutes to hours */
$user_tz = $hr_offset;
$_SESSION['user_tz_offset'] = $user_tz;
$_SESSION['got_tz'] = TRUE;
}
// if session value already set, get that
elseif ( $_SESSION['got_tz'] == TRUE ) {
$user_tz = $_SESSION['user_tz'];
}
// else post and submit javascript
else {
// get timezoneoffset value (JS)
// put tz value in hidden field
// auto-self-submit hidden field
$js_script = <<<JSH

<SCRIPT LANGUAGE="Javascript">
<!--
user_date = new Date();
user_offset = user_date.getTimezoneOffset();
form_str="<form name='tz_form' action='{$_SERVER['PHP_SELF']}' method='post'>";
input_str = "<input type='hidden' name='tz' id='tz' value='" + user_offset + "'></form>";

document.write(form_str);
document.write(input_str);
document.tz_form.submit();
//-->
</SCRIPT>

JSH;

// be sure to echo it to the browser
echo $js_script;

} /* end JS part */

// add clear button?
if ( $add_clear_button ) {
$clear_button = <<<CBHERE

<!-- clear button -->
<form action="{$_SERVER['PHP_SELF']}" method="post" name="reset">
<input type="submit" name="reset_tz" value="resubmit your timezone offset" />
</form>

CBHERE;

echo $clear_button;
}

$user_time = mktime(gmdate("G, i, s, n, d, Y")) - $_SESSION['user_tz_offset'];

return $user_time;

} /* end Fx */
/******************************/

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home