new Date().getTimezoneOffset()*(-1);
This JS function returns the UTC Time Zone of the machine in minutes. Is there any PHP function does the same thing?
Thank you..
<?php // RAY_easy_client_time.php
error_reporting(E_ALL);
// USE JAVASCRIPT TO GET THE CLIENT TIME AND COMPUTE THE OFFSET FROM THE SERVER TIME
// LOCATION OF THE SERVER - COULD BE ANYWHERE
date_default_timezone_set('America/Denver');
// DIFFERENCE OF SERVER TIME FROM UTC
$server_offset_seconds = date('Z');
// WHEN THE FORM IS SUBMITTED
if (!empty($_POST))
{
// JAVASCRIPT TELLS US THE CLIENT TIME OFFSET FROM GMT / UTC
$client_offset_minutes = $_POST["date_O"];
$client_offset_seconds = $client_offset_minutes * 60;
// THE TIME WE WANT AT THE CLIENT LOCATION
$client_timestring = 'TODAY 7:00AM';
// MAKE THE COMPUTATIONS, INCORPORATING THE OFFSET FROM GMT
$client_timestamp = strtotime($client_timestring) + $client_offset_seconds;
$server_timestamp = $client_timestamp + $server_offset_seconds;
$server_timestring = date('l, F j, Y \a\t g:i a', $server_timestamp);
echo "<br/>ACCORDING TO THE VALUE FROM PHP date Z";
echo "<br/>SERVER IS LOCATED $server_offset_seconds SECONDS FROM UTC";
echo "<br/>";
echo "<br/>ACCORDING TO THE VALUE FROM JS dateObject.getTimezoneOffset()";
echo "<br/>CLIENT IS LOCATED $client_offset_minutes MINUTES FROM UTC";
echo "<br/>";
echo "<br/>WHEN IT IS '$client_timestring' AT THE CLIENT, IT IS '$server_timestring' IN " . date_default_timezone_get();
}
// END OF PHP - USE HTML AND JS TO CREATE THE FORM
echo PHP_EOL; ?>
<form method="post">
<input name="date_O" id="dateTime_O" type="hidden" />
<input type="submit" value="CHECK CLIENT DATETIME" />
</form>
<!-- NOTE THIS WILL GIVE YOU THE VALUES AT PAGE-LOAD TIME, NOT AT SUBMIT TIME -->
<!-- MAN PAGE REF: http://www.w3schools.com/jsref/jsref_obj_date.asp -->
<script type="text/javascript">
var dateObject = new Date();
document.getElementById("dateTime_O").value = dateObject.getTimezoneOffset();
</script>
PHP, being server side, can only read what the client sends. It cannot tell the user timezone without being explicitly told by the user (or a user agent like the browser).
There are a couple ways to guess. You can look up the IP and guess timezone based on IP location by calling a location service (time expensive and can return incorrect results, I wouldn't recommend it).
You can also have your javascript make an ajax call to tell the server what the value for Date().getTimezoneOffset() is. Personally I would take this route.
Related
The code for everything is working except the looping. How do I loop my if-statement every minute?
I tried refreshing the page when the time matched the starting time of the task and it worked, but it would not check for the next minute.
$todoConn = mysqli_connect($server, $username, $password, $dbname);
$timeRn = date('h:i A');
echo $timeRn; // This is just a test to see the current time.
$select_query="SELECT * FROM wtdn";
$sqlResult=mysqli_query($todoConn,$select_query);
while($row=mysqli_fetch_array($sqlResult)) {
if ($timeRn == $row['time']) {
echo "<script>
Notification.requestPermission();
new Notification('".$row['task_text']."');
</script>"; // This is just a test
}
sleep(60); // Sleep for 60 sec
}
If the current time matches the task starting time, a notification should be sent.
First and foremost, this is not the most performative solution, but
it is the closest to a simple solution using the least amount of ajax.
You will need php, html and ajax to do it.
start.php:
<html>
<title>Monitoring task...</title>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="my_header" style="background-color:lightblue">
<p>div header here</p>
</div>
The rest of your html / php page is here...
</body>
<script>
function loadlink(){
$('#my_header').load('script_task.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink()
}, 2000); /* this will run after every 2 seconds - change to 60 seconds (60000) */
</script>
script_task.php
<?php
/* here the code to get the time tasks from the database */
$task_time_from_db = 1622689200; //exemple - Timestamp generated for Saturday, 30-Mar-2019 00:00:00 GMT+0000 using https://www.timestampconvert.com/
$current_time = time();
echo "<pre>This text is inside the script_task.php where the php time() function is updating: <h1>" . gmdate('m-d h:i:s \G\M\T', time()) . "</h1><br>";
echo "*** Warning: This solution is not performative. Depending on what you put in your pscript_task.php the server may get slow! ***<br>";
echo "Current time: " . $current_time . "<br>";
echo "Task time: " . $task_time_from_db . "<br>";
if($current_time >= $task_time_from_db){
echo "Macth! Run your code here!";
}
?>
This is a very basic project for a PHP class I am in - no databases involved so the data isn't going anywhere except the next page.
Currently, I am formatting the date on the page with the form using a hidden field, and it gets passed through in the URL post-formatting (with all the spaces punctuation). That satisfies the requirements of the assignment, but does not seem like the cleanest way to do this.
The form is "Comp2.php" and the page that displays the data is "Comp2b.php"
Here are the code segments in question:
(There are other fields in play of course, but I left them out since they are just text)
Comp2.php
<?php
if (isset($_POST['submit'])) {
$valid = true;
$dateadded = $_POST['dateadded'];
if ($valid) {
header("Location: Comp2b.php?albumid=$albumid&album=$album&artist=$artist&dateadded=$dateadded");
exit();
}
} else {
$albumid="";
$artist="";
$album="";
$price="";
$type="";
$playlists[0]="";
$genre="";
$tracks="";
}
?>
<form method="post" action="Comp2.php">
<?php $currentDate = date('l, F d, Y h:i:s a.') ?>
<input type="hidden" name="dateadded" value="<?php echo $currentDate; ?>">
Then the rest of the form continues...
This is
Comp2b.php:
<?php
echo "Album ID: <strong>";
echo $_GET['albumid']."</strong><p><strong>".$_GET['album']."</strong> by <strong>".$_GET['artist']."</strong> added on ".$_GET['dateadded'];
?>
How can I pass something like date() or time() through the form, and do the formatting i.e., date('l, F d, Y h:i:s a.', $dateadded) on my second page instead of passing a full string through the URL?
In the first page put a simple time() in the hidden field
<input type="hidden" name="dateadded" value="<?php echo time(); ?>">
Then in the second page output that timestamp formatted any way you like
<?php
echo "Album ID: <strong>";
echo $_POST['albumid'];
echo '</strong><p><strong>'.$_POST['album'];
echo '</strong> by <strong>' . $_POST['artist'];
echo ' </strong> added on ' . date('l, F d, Y h:i:s a.', $_POST['dateadded']);
?>
Reasons:
time() generates a simple number like 876243672834 which is much easier to pass around and less likely to cause confusion.
'date()` can have 2 parameter, the first is a format, and the second is a timestamp representing a date and time in unix format.
Also because your form <form method="post" has a method of post the data will end up in the $_POST array and not the $_GET array
The $_GET array is populated when you do things like <a href="xxx.php?a=1&b=2"> or use <form method="GET"
I'm building an application on WordPress wherein I have a single form with two entries:
1) content of the tweet
2) time at which the tweet should be posted on the user's Twitter timeline
Form:
<form method = "POST">
<input type = "text" name = "tweet1">
<input type = "datetime-local" name = "date1">
<input type = "submit">
</form>
Now, on submitting the form, I want to post the content of the text field to be posted on the user's Twitter timeline at the time specified by the user in the form. $_SESSION['x'] and $_SESSION['y'] stores the user's oauth_token and oauth_token_secret respectively.
<?php
if(isset($_POST['submitted']))
{
function do_this_one()
{
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['x'], $_SESSION['y']);
$response = $connection->post("statuses/update", array('status' => $_POST['tweet1']));
}
date_default_timezone_set('Asia/Calcutta');
$myDate = strtotime($_POST['date1']);
$now = time();
$ti_one = $myDate - $now;
echo time() + $ti_one;
add_action( 'my_new_event','do_this_one' );
wp_schedule_single_event(time() + $ti_one, 'my_new_event' );
?>
$ti_one variable basically stores the time in seconds between now and the time specified by the user. For example, if the current time is 2:00 PM, then if the time specified by the user in the form is 2:03 PM, then $ti_one would be equal to 180 seconds. That's the reason why I'm scheduling the event at time() + $ti_one in:
wp_schedule_single_event(time() + $ti_one, 'my_new_event' );
However, on submitting the form, the tweet is not being posted at the specified time. The above code ie code for the form and the PHP code is inside callback.php, which is the page that the users are redirected to after granting permission to the OAuth client.
What seems to be wrong with my code? Am I scheduling the event incorrectly?
This is going to be a bit difficult to explain but I will try my best to explain it as good as i can.
I am passing Data from an input textfield on one page (page1.php) to a Select form on another page (page2.php).
This works as should.
the Select Form contains some PHP timezones and when a timezone is selected, the page page will echo the current time for that timezone.
This also works as it should.
The problem is when I enter a timezone name in the input textfield on (page1.php) , it will show the name in the Select Form on (page2.php) BUT it will not echo its current time and it will throw out this error:
Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct(): Unknown or bad timezone (London)' in page2.php:16 Stack trace: #0 on line 16.
when infact the timezone London exists in the Select Form Options and if I enter/search for London directly in the select form, it will echo the current time for that timezone but it will NOT if the timezone name was entered in the input textfield on page1.php and it was passed to the select form on page2.php!
here is what I have on page2.php:
<?php
if( isset($_POST['submit']))
{
//be sure to validate and clean your variables
$timezone2 = htmlentities($_POST['timezone2']);
//then you can use them in a PHP function.
function get_timezone_offset( $remote_tz ) {
$timezone2 = new DateTimeZone ( $remote_tz ); ----->>> Line 16 is here.
$datetime2 = new DateTime ("now", $timezone2);
$offset = $timezone2->getOffset($datetime2);
return $offset;
}
$offset = get_timezone_offset($timezone2);
}
?>
<?php
$options = array();
$options[$_POST["location"]] = $_POST["location"]; <<<<<<----- Data from input textfield on page1.php
$options["Africa/Addis_Ababa"] = "Addis Ababa"; <<<<<<----- Select Form Options
$options["Europe/London"] = "London"; <<<<<<----- Select Form Options
?>
and here is the Select Form on page2.php
<form id="myForm" name="myForm" class="myForm" method="post" action="page2.php">
<select style="font-size:9px;" name="timezone2" id="timezone2" class="timezone2">
<?php
foreach($options as $key => $value)
{
echo '<option value="'. $key .'" label="'. $value .'">'.$value.'</option>';
}
?>
<option value="<?php echo $_POST["location"]; ?>"><?php echo $_POST["location"]; ?></option>
</select>
</div>
<div id="myBtn" style="position:relative; float:left; width: 228px; margin-top:50px; margin-left:350px;"><input type="submit" name="submit" id="submit" class="submit" value="Search"/></div>
</form>
and here is the input textfield on page1.php
<form method="post" action="../page2.php">
<input name="location" type="text" value="Search"/>
<button type="submit">Search</button>
</form>
could someone please point me in the right direction?
You're going about this wrong for a few reasons. Firstly, the list of possible timezones is finite so get rid of the text field and just use a dropdown.
Second, you can remove\rename the items in the dropdown all you want but just remember that since you are saving the offset and not the tz name you can never go back (my example will show you exactly why that is if you play with it). Usually, it is best to store the name and not the offset so that you can manage daylight savings properly. You'll notice that to get this system to work I need to call date('I') to find out if it is daylight savings which is really bad (just because it's daylight saving in my server TZ doesn't mean it is in the users TZ). If you saved the TZ name instead you could defer that logic to PHP and just use whatever offset it currently is. This may not seem important in this simplistic example but if you ever tried to store that offset or calculate future\past times using it you'll definitely have troubles.
One other tiny thing is that it is odd to put function definitions inside of 'if' statements. In PHP all function definitions are global so it will be available regardless of whether the 'if' condition is true. The problem with doing that is now you've obscured your logic with no gain. It is easier and clearer to put that elsewhere.
I've rewritten your code to be a little nicer and to actually work as you are using it but I've left out a few details (like aliasing the TZ names [which you seem to have a handle on how to do] and switching to using TZ names instead of offsets [because that may break other code you have]) but I encourage you to fix those as well.
<?php
$tz_offset=0;
function get_offset_time($offset=0) {
$original=new DateTime("now");
$timezoneName=timezone_name_from_abbr("", $offset, date('I'));
if(!$timezoneName) die('ERROR: Unknown timezone \''.($offset/3600).'\'');
$oTZ=new DateTimezone($timezoneName);
$modified = $original->setTimezone($oTZ);
return $modified->format('Y-m-d H:i:s');
}
function get_timezone_offset($tz_name=null) {
if(!$tz_name) return 0; // If we have invalid data then return before we error
$tz=new DateTimeZone($tz_name);
$dt=new DateTime("now", $tz);
return $tz->getOffset($dt);
}
function enumerate_tz($tz_select=null) {
global $tz_offset;
$tz_ident=DateTimeZone::listIdentifiers();
foreach($tz_ident as $val) {
$tmp_offset=get_timezone_offset($val);
if($val=='UTC'||$tmp_offset)
echo '<option value="'.$val.'" '. ($tmp_offset==$tz_offset?' selected':''). '>'.
$val. ' [ '.($tmp_offset/3600).' ]'. // If you'd like to customize the viewable names for each TZ you may do so here
'</option>';
}
}
if(isset($_POST['tz_input']) && $_POST['tz_input']) {
$tz_input=htmlentities($_POST['tz_input']);
$tz_offset=get_timezone_offset($tz_input);
}
echo '<html><title>Timezone Select</title><body>'.
'<p>The current timezone offset is: '. ($tz_offset? ($tz_offset/3600): '0'). '</p>';
echo '<p>The current time is: '. get_offset_time($tz_offset). '</p>';
echo '<form method=post><select name=tz_input>';
enumerate_tz($tz_offset); // You'll notice that this list duplicates many of the timezones so that after selecting one the next
// time through it'll often select a different one. If you want to fix that you'll need to save the actually offset name instead of an offset.
echo '</select><input type=submit value=Search />'.
'</form></body>';
?>
EDIT: One other thing to note is that PHP's timezone_name_from_abbr() function is not complete. Some timezone offsets will not return a TimeZone name. You must account for that as well. For example, even though PHP understands the 'Pacific/Midway' timezone it cannot find it when doing a reverse lookup. I've updated the code so that won't cause a hard error anymore.
EDIT2: I can see that you aren't going to be happy until someone shows you how to shine that turd. Here you go:
function getOptionDX($val, $option_array) {
if(!isset($option_array)||!is_array($option_array)||!count($option_array)>0||!$val) return null;
$val=htmlentities($val);
if(isset($option_array[$val])) return $val;
$new_val=array_search($val, $option_array);
return $new_val!==FALSE?$new_val: null;
}
Add this to your code and replace the call to htmlentities with a call to this:
$timezone2 = getOptionDX($_POST['timezone2'], $options);
Lastly, change this line:
if($timezone2) $offset = get_timezone_offset($timezone2);
If the user enters the TZ manually and it is correct then skip page2.php. This is as close to an answer as can be given if you don't want to change anything. The fact is that your logic is flawed in the first place (that is not meant to be a jab but it is true).
EDIT3: IDK what was wrong but here is my full code listing with the fixes you asked for:
<?php
$offset=0; $timezone2='';
$options = array();
$options["Africa/Addis_Ababa"] = "Addis Ababa";
$options["Europe/London"] = "London";
$options["America/Chicago"] = "The Windy City";
function getOptionDX($val, $option_array) {
if(!isset($option_array)||!is_array($option_array)||!count($option_array)>0||!$val) return null;
$val=htmlentities(ucwords(strtolower($val)));
if(isset($option_array[$val])) return $val;
$new_val=array_search($val, $option_array);
return $new_val!==FALSE?$new_val: null;
}
function get_timezone_offset( $remote_tz ) {
$timezone2=new DateTimeZone($remote_tz);
$datetime2=new DateTime("now", $timezone2);
$offset=$timezone2->getOffset($datetime2);
return $offset;
}
if(isset($_POST['location'])) {
$addLoc=getOptionDX($_POST['location'], $options);
if(isset($addLoc)) $options[$addLoc]=$_POST['location'];
else header('Location: '. $_SERVER['SCRIPT_NAME']);
}
if(isset($_POST['timezone2'])) {
$timezone2=htmlentities($_POST['timezone2']);
$offset=get_timezone_offset($timezone2);
}
if(isset($_GET['page2'])) {
?>
<form method=post action=?page2>
<select name=timezone2>
<?php foreach($options as $key=>$value) echo "\t".'<option value="'. $key .'"'.(get_timezone_offset($key)==$offset?' selected':'').'>'.$value.'</option>'."\n"; ?>
</select>
<input type=hidden name=location type="text" value="<?php echo $_POST['location']; ?>"/>
</div>
<input type=submit value=Search>
</form>
<p>Current Offset: <?php echo $offset/3600; ?></p>
<p>Current Time: <?php echo gmdate('Y-m-d H:i:s'); ?> UTC</p>
<p>Current Time: <?php echo gmdate('Y-m-d H:i:s', time()+$offset).' '. $timezone2; ?> </p>
<?php
} else {
?>
<form method=post action=?page2>
<input name=location type=text value=""/>
<button type=submit>Search</button>
</form>
<?php
}
?>
I've tested this and know it works, if that isn't enough to answer your question then I give up. I'm starting to think that you really want a way to invent new timezones which don't exist. That isn't possible. You can alias those which already exists as I've done here which is as close as you're ever going to get. Logically, time zones can only range from -12:00 to +12:00 and nearly every known timezone is already accounted for so you really have no choice but to rethink your design if this isn't enough.
Assume that I'm adding the date / time into a mysql database and have the following (small for once) chunk of code.
<input type="text" name="date">Leave time null for current<br />
<input type="Submit" name="submit" value="submit">
The Following is the form that catches that
$radate=$_POST['date'];
if ($radate=="")
$radate = date('Y-m-d H:i:s');
else {}
I've tried entering "2011-08-14 19:15:25" and it has returned all 0's, can someone help me out with this? Thanks a ton!
You would probably be better off using strtotime() to validate the date/time submitted, if it's a freeform date entry field especially. Otherwise, someone may miss-enter a date/time and unexpectedly have it use the current date/time instead.
$radate_valid = false;
$radate = $_POST['date'];
if (!$radate)
$radate = date('Y-m-d H:i:s');
if (strtotime($radate) === false)
$radate_valid = false;
else
$radate_valid = true;
// Somewhere else
if ($radate_valid !== true)
/* Do something to warn the user. */
http://codepad.org/x2eZay0Q
If you used dropdowns, and the time was not a factor, you could also use checkdate(), although from your example it looks like you do need the time.
However, what you have posted should work. Here is an example using your date you provided:
http://codepad.org/BK1yqyMT
(And here without fixing the if block: http://codepad.org/p3CfmOJK)