I have been trying to resolve this issue and have spent hours to find the reason why this is keep happening with no avail.
I really don't know what I am doing wrong!
I am trying to create a simple time difference using timezones in PHP. I need to allow the users to choose the both locations on the page. for this purpose I am using two dropdown lists which will have all the timezones in them.
Every time I run the code/page on my server, I get this error:
Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (origin_tz)' in /home/a1385482/public_html/timediff.php:204
Stack trace:
#0 /home/a1385482/public_html/timediff.php(204): DateTimeZone->__construct('origin_tz')
#1 /home/a1385482/public_html/timediff.php(215): get_timezone_offset('origin_tz', 'remote_tz')
#2 {main} thrown in /home/a1385482/public_html/timediff.php on line 204
Here is the full page code:
<?php
echo "Version: " . phpversion();
?>
<form method="post" action="">
<select name="timezone2" id="timezone2" class="timezone2">
<option value="Pacific/Midway">(GMT-11:00) Midway Island, Samoa</option>
.. snip ..
</select>
<select name="timezone1" id="timezone1" class="timezone1">
<option value="Pacific/Midway">(GMT-11:00) Midway Island, Samoa</option>
.. snip ..
</select>
<input type="submit" name="submit" value="send"/>
</form>
<?php
if( isset($_POST['submit']))
{
//be sure to validate and clean your variables
$timezone1 = htmlentities($_POST['timezone1']);
$timezone2 = htmlentities($_POST['timezone2']);
//then you can use them in a PHP function.
function get_timezone_offset( $origin_tz, $remote_tz ) {
$timezone1 = new DateTimeZone( $origin_tz );
$timezone2 = new DateTimeZone( $remote_tz );
$datetime1 = new DateTime("now", $timezone1);
$datetime2 = new DateTime("now", $timezone2);
$offset = $timezone1->getOffset($datetime1) - $timezone2->getOffset($datetime2);
return $offset;
}
$offset = get_timezone_offset('origin_tz', 'remote_tz');
echo $offset/3600;
}
?>
could someone please shed a light on this as I am stuck on this one for almost 8 hours.
get_timezone_offsetwith 2 strings. I don't think'origin_tz'is a valid timezone.htmlentitiesshould only be used when echoing onto the screen. It's not for sanitizing input.