How to count time from list of timestamps in PHP? - php

I want to count time spent on the website. I have a list of timestamps for each user, the smallest interval between each timestamp is at least 60 seconds.
Edit:
Here is my code, can't group them by range of 100 seconds
<?php
$numbers = array(1503541542,1503541602,1503541662,1503541722,1503541782,1503541842,1503541902,1503541962,1503542022,1503542082,1503542142,1503542202,1503542262,1503542322,1503542382,1503542442,1503542502,1503542562,1503542622,1503542682,1503542742,1503542798,1503542799,1503542859,1503542877,1503542878,1503542938,1503542961,1503542962,1503543022,1503543079,1503543080,1503543140,1503543200,1503543221,1503543221,1503543281,1503543341,1503543401,1503543461,1503543521,1503543581,1503543641,1503543701,1503543761,1503543821,1503543881,1503543941,1503544001,1503544061,1503544121,1503544181,1503544241,1503544301,1503544361,1503544421,1503544481,1503544541,1503544601,1503544661,1503544721,1503544781,1503544841,1503544901,1503545055,1503545056,1503545060,1503545061,1503545120,1503545173,1503545174,1503545181,1503545233,1503545240,1503545293,1503545301,1503545304,1503545304,1503545364,1503545424,1503545484,1503545544,1503545604,1503545664,1503545724,1503545784,1503545844,1503545904,1503545964,1503546024,1503546084,1503546144,1503546204,1503546264,1503546324,1503546358,1503546359,1503546419,1503546479,1503546539,1503546599,1503546659,1503546719,1503546779,1503546839,1503546899,1503546959,1503547019,1503547079,1503547139,1503547167,1503547167,1503547199,1503547218,1503547218,1503547254,1503547254,1503547259,1503547281,1503547282,1503547319,1503547340,1503547341,1503547379,1503547401,1503547439,1503547461,1503547499,1503547521,1503547559,1503547581,1503547619,1503547641,1503547679,1503547701,1503547739,1503547761,1503547799,1503547821,1503547859,1503547881,1503547919,1503547941,1503547979,1503548001,1503548039,1503548061,1503548099,1503548121,1503548159,1503548181,1503548219,1503548240);
// $numbers = array(10, 30, 230, 240, 250, 260);
$result = array();
while (count($numbers) > 0) {
$begin = reset($numbers);
$end = array_shift($numbers);
while (in_array($end + 100, $numbers)){
$end = array_shift($numbers);
}
$beginAndEnd = array_unique(array($begin, $end));
$result[] = implode('-', $beginAndEnd);
}
print_r($result);
?>
Thank you in advance

The Best way to get user time stamps on a particular website is to use function "load" and "onunload", below is the code :
<!DOCTYPE html>
<html>
<head>
<title>Collect time</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function()
{
var start = null;
$(window).load(function(event) {
start = event.timeStamp;
});
$(window).onunload(function(event) {
var time = event.timeStamp - start;
$.post('/collect-user-time/ajax-backend.php', {time: time});
})
});
</script>
</head>
<body>
</body>
</html>
And backend script:
<?php
$time = intval($_POST['time']);
if (!file_exists('data.txt')) {
file_put_contents('data.txt', $time . "\n");
} else {
file_put_contents('data.txt', $time . "\n", FILE_APPEND);
}

Hum, your question is unclear but if I understand, this is my idea :
Add 2 session variables :
1 var to register old page on reload and update it on reload
1 var to register timestamp and update it on reload
Look this :
if(isset($_SESSION['page']) && isset($_SESSION['timestamp'])){
//REGISTER WHERE YOU WANT : BDD, LOGFILE...
//$userStay=$db->prepare();
//fopen('userStay', 'a+');
//WITH THESE DATA
$time = time() - $_SESSION['timestamp'];
$page = $_SESSION['page'];
}
$_SESSION['page']=$_SERVER['REQUEST_URI'];
$_SESSION['timestamp']=time();

Related

how to refresh page in a specific time

i tried this code in my wp page but its not work
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
date("d-m-Y H:i:s");
$time= date("H:i:s");
if($time == "03:40:00")
{
echo "The new page loading in 10 seconds!";
header("Refresh: $sec; url=$page");
}
?>
You can't do this in PHP, what you can do for such a task is to calculate a time difference and make it in seconds and set the header for the page to be refreshed after the time diff in seconds, something like this:
<?php
$page = $_SERVER['PHP_SELF'];
$datetime1 = new DateTime('2020-05-23 18:20:10');
$datetime2 = new DateTime('2020-05-23 18:20:30');
$interval = $datetime2->diff($datetime2);
$diff = $datetime2->getTimestamp() - $datetime1->getTimestamp(); // diff in seconds
// you can just have `redirect` queryString params passed like this.
if(empty($_GET['redirect'])) {
header("Refresh: $diff; url=$page" . "?redirect=1");
}
Something to point out here, is to use tag to do the refresh in your page instead of using header(), it feels cleaner to me as implementation, specially if you already have a template engine:
<meta http-equiv="refresh" content="20">
You can place the below code in your header and test. I hope this helps.
if ($time == "03:40:00") {
echo "The new page loading in 10 seconds!";
echo "<meta http-equiv='refresh' content='3'>";
}
Note: The above used meta tag is used to define time intervals to refresh the document itself. Modify the values in "content" attribute of meta tag as you wish to refresh the page
Thank you everyone, problem solved, i used javascript, function auto-run
<script>
(function myFunction() {
var time = new Date().getHours()
if( time == "02" ) {
setTimeout(function(){
window.location = 'your url';
}, 5000);
}
})();
</script>
this code better i think, thank you Andrew Moore !
<script>
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(16,30,0); //Will refresh the page at 4:30pm
</script>

countdown timer, no refresh on page change

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var time_left = 50;
var cinterval;
var timestatus=1;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 0){
clearInterval(cinterval);
}
}
function resumetime()
{
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart()
{
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function stopstarttime()
{
if(timestatus==1)
{
clearInterval(cinterval);
document.getElementById('stopbutton').value="Start";
timestatus=0;
}
else
{
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
document.getElementById('stopbutton').value="Stop";
timestatus=1;
}
}
defaultstart();
</SCRIPT>
</HEAD>
<body>
Redirecting In <span id="countdown">50</span>.
<INPUT TYPE="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</HTML>
I am beginner. I have 10 questionnaire pages. Is there any possibility that this timer do not refresh on page change/refresh. And it should work differently for different users. If possible please help me.
You can store the timestamp the timer should end in a cookie or localStorage. Then use this cookie to display the correct counter. This solution is not 100% safe (the user can alter the value of this cookie to make the counter last longer if they know how to alter cookies/localStorage via the developer console), so don't use it in situations where this is bad.
var timeLeft = 50;
if( window.localStorage ) {
if( !localStorage.getItem( 'endTimer' ) ) {
localStorage.setItem( 'endTimer', new Date().getTime() + (timeLeft * 1000) );
}
}
The time in miliseconds left is then localStorage.getItem( 'endTimer' ) - new Date().getTime().

UTC clock based on server time?

I have a JavaScript clock that gets the time in UTC, it currently works, but the time is based off the client's computer. What could I do to base the time off of the server instead? I am using PHP as the server scripting language. I would like to not use AJAX.
<?php
$year = date("Y");
$month = date("m");
$day = date("d");
$hour = date("h");
$minute = date("i");
$str = $year . $month . $day . $hour . $minute;
echo "history.pushState('', 'title', '?q=$str');";
echo "var ct = '$str';";
?>
function dT(){
var d = new Date();
d = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
d.setTime(d.getTime());
v = d.getFullYear() + "" +
padstr(d.getMonth()) + "" +
padstr(d.getDate()) + "" +
padstr(d.getHours()) + "" +
padstr(d.getMinutes()) + "" + padstr(d.getSeconds());
if(ct !== v){
history.pushState('', 'title', '?q=' + v);
ct = v;
}
setTimeout('dT()', 1000);
}
dT();
Edit
var a = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
document.getElementById("time").innerHTML = a;
function clock_tick(){
var time = moment(a);
time.add('second', 1);
a = time.format("YYYY-MM-DD HH:MM:SS");
document.getElementById("time").innerHTML = a;
setTimeout("clock_tick()", 1000);
}
clock_tick();
This should get you started. You don't need to use moment.js, but I wanted to try it out since someone suggested it.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="moment.js"></script>
<script language="javascript">
$(function() {
$('#clock')[0].innerHTML = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
clock_tick();
});
function clock_tick(){
var clock_div = $('#clock')[0];
var time = moment(clock_div.innerHTML);
time.add('second', 1);
clock_div.innerHTML = time.format("YYYY-MM-DD hh:mm:ss");
setTimeout("clock_tick()", 1000);
}
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>
Then as I stated earlier you may need to set:
date_default_timezone_set("UTC");
Reference Link:
http://php.net/manual/en/function.date.php
moment(give ur value).format('L');
that will returns the local time. see the below url it got lots of formatting options, will fit your needs.
http://momentjs.com/

Countdown timer built on PHP and jQuery?

After spending the last 45 minutes looking around for a solution, I can't seem to find an easy solution to creating a countdown timer using PHP and jQuery. Most already built scripts I've found are based purely on jQuery which require a ton of code, and more parameters then they should, plus, adaptability is pretty hard.
Here's my situation;
PHP:
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
jQuery:
$(document).ready(function name() {
$("#this").load( function() {
setTimeout("name()", 1000)
}
}
});
HTML:
<div id="this"><?php echo($countdown); ?></div>
My idea is that, every second, #this is reloaded, giving a new value to it's contents, and as $countdown isn't a static variable, a new value will be loaded each time. This removes the need to deal with sessions (as a basic javascript countdown timer would reset on pageload, etc).
I would've though this would have worked, until I realized that the event binder .load() doesn't reload #this (I know silly me), so I guess what I'm wondering is - is there an event binder I can use to make this work or is there a way to get the functionality I'm looking for, without using a jQuery plugin (which doesn't match exactly what I want anyway)?
You should use Keith Wood's countdown timer: http://keith-wood.name/countdown.html
It is extremely easy to use.
All you have to do is
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});
Here's the fiddle: http://jsfiddle.net/tqyj4/289/
OK, I know that an id is not a variable, but don't use this as an ID. It is makes people cringe.
To the rest, don't reload the value, set a value in JS in PHP and then count down.
// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";
Then:
// this is a helper function.
function lpad( input, len, padstr )
{
if( !padstr ) padstr = " "; // this is the normal default for pad.
var ret = String( input );
var dlen = ret.length - len;
if( dlen > 0 ) return ret;
for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
return ret;
}
$(document).ready(function name() {
$("#timer").load( function() { // I changed the id
$timer = $("timer"); // might as well cache it.
// interval, not timeout. interval repeats
var intval = setInterval(function(){
t += 500; // decrease the difference in time
if( t >= ft )
{
t = ft; // prevent negative time.
clearInterval( intval ) // cleanup when done.
}
var dt = new Date(ft - t);
$timer.innerHTML = dt.getHours() + ":" +
// pad to make sure it is always 2 digits
lpad( dt.getMinutes(), 2, '0' ) + ":" +
lpad( dt.getSeconds(), 2, '0' );
}, 500) // increments of .5 seconds are more accurate
}
}
});
Once php has loaded a particular amount of time for the user, can you explain why this wouldn't be sufficient for your needs:
$(function(){
$timerdiv = $("#this");
timer();
});
function timer()
{
$timerdiv.html((int)$timerdiv.html() - 1);
setTimeout(timer, 1000);
}
You are very close in your original code. Here's a modification to your code below that works as described, or at least so I think - I know it works, but am not sure if it meets your requirements, they were a little unclear. Obviously if you reload the page, you would have to rely on the PHP output to be different in order for the counter to not reset. Just to note though, I'm not entirely sure why you would use the .load function - that function is really just a wrapper for an AJAX call to grab the contents of another page and insert it into the selected div. I believe what you're looking for is the .html() function to change the contents of the selected div using the content available in the DOM vs. making an AJAX request.
var timer;
$(document).ready(
name();
);
function name() {
//clear the timer
clearTimeout(timer);
//reset the timer
timer = setTimeout("name()", 1000);
//grab the current time value in the div
var time = $("#this").html();
//split times
var time_splits = time.split(":");
//add up total seconds
var total_time = (parseInt(time_splits[0])*60*60) + (parseInt(time_splits[1])*60) + parseInt(time_splits[2]);
//subtract 1 second from time
total_time -= 1;
//turn total time back in hours, minutes, and seconds
var hours = parseInt(total_time / 3600);
total_time %= 3600;
var minutes = parseInt(total_time / 60);
var seconds = total_time % 60;
//set new time variable
var new_time = (hours < 10 ? "0" : "") + hours + (minutes < 10 ? ":0" : ":" ) + minutes + (seconds < 10 ? ":0" : ":" ) + seconds;
//set html to new time
$("#this").html(new_time);
}
$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$secondsDiff = $targetDate – $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
<script type=”text/javascript”>
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdowncont/’; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00″; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdown/’; ?>”,
async: false,
success: function(html){
}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url
}
}
</script>
<?php
if($date1 < $futureDate && ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>
#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>
For more information visit urfusion
#epascarello answer for your question in you need to pass the loop value in selector with id for example
$("#timer<? php echo $loopval; ?>")
and also call the it in the
<div id="timer<?php echo $loopval; ?>">
</div>

PHP JavaScript Countdown Timer

I need to make a countdown timer that displays a specific number of minutes and seconds counting down - not a countdown to a certain date.
And depending on a variable, change these numbers.
So for $video == 1, I need to display on the page: 8 minutes & 54 seconds (counting down)
And for $video == 2, I need to display on the page: 5 minutes & 01 seconds (counting down)
I also need the countdown display to disappear after the time has elapsed, but maybe I should put that into a different question.
The problem I'm having is the all the countdown scripts I can find deal with counting down to a specific date.
Everything you need, just enter the total time in seconds in the <span> tags. 30 and 120 here for demo. Should work if you copy and paste directly into a webpage. Add and edit code as needed.
<span id="countdown-1">30 seconds</span>
<span id="countdown-2">120 seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
/**
* Countdown function
* Clock count downs to 0:00 then hides the element holding the clock
* #param id Element ID of clock placeholder
* #param timer Total seconds to display clock
*/
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
document.getElementById(id).style.display = 'none';
}
}
</script>
Try:
var x, secs = 600; //declared globally
x = setInterval(myFunc, 1000);
function myFunc()
{
document.getElementById('timer').innerHTML = secs; //assuming there is a label with id 'timer'
secs --;
if(secs == 0)
{
document.getElementById('timer').style.hidden = true;
clearInterval(x);
}
}
There is a countdown script located at http://javascript.internet.com/time-date/countdown-timer.html that doesn't countdown to a date but rather a specified amount of minutes.
The code may be customized as follows to get the desired effect
<?php
if ($video===1){
$time="8:54";
}
if ($video===2){
$time="5:01";
}
?>
<script type="text/javascript" src="countDown.js"></script>
<form name="cd">
<input id="txt" readonly="true" type="text" value="<?php echo $time; ?>" border="0" name="disp">
</form>
Make sure that the contents of countDown.js looks like this:
/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Neill Broderick :: http://www.bespoke-software-solutions.co.uk/downloads/downjs.php */
var mins
var secs;
function cd() {
mins = 1 * m("10"); // change minutes here
secs = 0 + s(":01"); // change seconds here (always add an additional second to your total)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
document.cd.disp.value = dis(mins,secs); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
window.alert("Time is up. Press OK to continue."); // change timeout message as required
// window.location = "yourpage.htm" // redirects to specified page once timer ends and ok button is pressed
} else {
cd = setTimeout("redo()",1000);
}
}
function init() {
cd();
}
window.onload = init;
<?php
$countDownTime = 0;
if ($video == 1) $countDownTime = (8*60 + 54);
else if ($video == 2) $countDownTime = (5*60 + 1);
echo '<script>var countdownTime="' . $countDownTime . '";</script>"';
?>
<script>
<!-- as per the hyper linked reference below -->
$(selector).countdown({until: countdownTime});
</script>
Using the following library, you can implement a JQuery timer using the var countdownTime you specify above...
http://keith-wood.name/countdown.html <-- tutorial on the first page!
Edit Replaced $someTimeInSeconds with $countDownTime
Ok, I'm looking at doing something similar. Currently I have a simple countdown timer that is based off of current time that counts down every 30min. The problem is that I have to use a meta refresh to update it. I'm wondering if a combination of javascript and PHP might be a simpler solution to this answer. Use javascript to call the php code and automatically update it? Maybe set a variable for the time in the php script to be called with javascript? Well, here's the code I have that might help. I'm still learning.
$minutes_left = ($minutes)?((30 - $minutes)-(($seconds)?1:0)):0;
$minutes_left = str_pad ($minutes_left , 2, '0', STR_PAD_LEFT);
$seconds_left = ($seconds)?(60 - $seconds):0;
$seconds_left = str_pad ($seconds_left , 2, '0', STR_PAD_LEFT);
echo '<center><h1 style="font-color:white;">Next station break in: '.$minutes_left.'m '.$seconds_left.'s</h2></center>';
?>
I just have to figure out how to get it to reset itself at the end of every 30min and to update without meta refresh.

Categories