Php subtract time saved in session with current time - php

i am using jquery countdown timer but the problem is that timer start from value set every time on page refresh . I want to get time on first time and Save in PHP Session and subtract second time from frist time and update session etc. In Simple Word i want to create php countdown timer run only 50 using php
here is my controller code
public function actionViewtimer($id) {
$session = Yii::app()->session;
$this->layout = 'countdownlayout';
if (empty($session['countdowntime'])) {
$orderTime = microtime(true); #when user first time enter timer start from 50 mins
$session->add('countdowntime', array($orderTime)); //replace this line
} else {
$time_end = microtime(true);
$orderTime = $time_end - $time_start;
unset($session['countdowntime']);//unset old session
$session->add('countdowntime', array($orderTime)); //when user enter second
}
$getMinutes = $getMinutes_from_orderTime ; #please tell me how we extact minutes and pass them to view
$session->add('timersession', array($rand));
$this->render('viewtimerpage', array(
'getMinutes' => $getMinutes
));
}
here is my jquery code
<script>
$(function() {
$('#xlarge').countdowntimer({
minutes: 50<?php echo $getMinutes; ?>,
size: "lg",
timeUp: timeisUp
});
});
function timeisUp() {
alert('Time Complete');
return false;
}
</script>

Sorry, I've not used Yii so this example will be in plain PHP.
session_start();
if(!isset($_POST['counter']) || !is_array($_POST['counter')) {
$duration = 50;
$counter = array(
'start_time' => new DateTime()->format('Y-m-d H:i:s'),
'end_time' => new DateTime()->modify("+{$duration} minute")->format('Y-m-d H:i:s'),
'duration' => $duration
);
$_SESSION['counter'] = $counter;
}
$counter = $_POST['counter'];
$now = new DateTime();
$end_time = new DateTime($counter['end_time']);
$time_left = $end_time->getTimestamp() - $now->getTimestamp();
echo "{$time_left} seconds left";
This should be simple enough to convert, and you can easily convert seconds to minutes.

Don't destroy the session variable. Just set it the first time when its empty and then plug that value always into your countdown timer.
Inside you action
$session = Yii::app()->session;
$this->layout = 'countdownlayout';
if (empty($session['countdowntime'])) {
$date = new DateTime();
$date->modify('+50 minutes'); // Add 50 minutes to current time
$session['countdowntime'] = $date->format('Y/m/d H:i:s'); // Store date in session
}
$this->render('viewtimerpage', array(
'countdowntime' => $session['countdowntime'];
));
jQuery Code
$(function() {
$('#xlarge').countdowntimer({
dateAndTime : "<?php echo $countdowntime; ?>",
size: "lg",
timeUp: timeisUp
});
});

As I understand you want to show difference between 2 dates. Default value = 50 minutes(value for session if user first time opened page). If user refresh page after 10 minutes in view must show difference(40). It will be something like that:
public function actionViewtimer($id) {
$this->layout = 'countdownlayout';
/** #var CHttpSession $session */
$session = Yii::app()->session;
$minutes = 50; //default value for minutes
if (!$session->offsetExists('countdowntime')) {
$session->add('countdowntime', new DateTime()); //set value to session
} else {
$timeEnd = new DateTime();
/** #var DateTime $countDownTime */
$countDownTime = $session->get('countdowntime');
$interval = $countDownTime->diff($timeEnd);
$countMinutes = $interval->days * 24 * 60;
$countMinutes += $interval->h * 60;
$countMinutes += $interval->i;
$minutes -= $countMinutes;
$session->add('countdowntime', $timeEnd); //refresh value
}
// $session->add('timersession', array($rand)); don't know for what is it
$this->render('viewtimerpage', array(
'getMinutes' => $minutes
));
}
And js:
<script>
$(function() {
$('#xlarge').countdowntimer({
minutes: <?php echo $getMinutes; ?>, //without 50

Related

Get time data from DB - Laravel

I want to give an alert when a condition is met in a day time, right now I get the hours statically
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
but I want to get the established schedule from the DB
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
if ($hour1 > $hour2) {
Session::flash('message', 'ABIERTO!');
Session::flash('', '');
}
elseif ($hour1 < $hour2 ) {
Session::flash('message', 'SHOP CLOSED!');
Session::flash('alert-class', 'alert-danger');
}
I already created the model on table status
help pls
You can try like this
$hour1 = DateTime::createFromFormat('H:i', $status->open);
$hour2 = DateTime::createFromFormat('H:i', $status->closed);
OR just simply
$hour1 = new DateTime($status->open);
$hour2 = new DateTime($status->closed);
Then just make conditional
if ($hour1 > $hour2)
// what to do

Get Time From 5 Minutes Prior

I'm working on User Functions for the CMS I'm working on and I have users updated on each page load Using
if(User("online") == true) {
LastOnlineUpdate($_SESSION['key']['userid']);
}
(Yes User Online Works, That's my function to check online users)
And now my times are updated correctly hooking into the LastOnlineUpdate function then running my class function
public function SessionUpdate($arg) {
$query = <<<SQL
UPDATE {$this->tprefix}online
SET remote = :remote, timestamp = :timestamp
WHERE userid = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array(
':remote' => $_SERVER['REMOTE_ADDR'],
':timestamp' => time(),
':arg' => $arg,
));
}
Now whenever I go through my pages it updates the user by having the first code within my preloaded file, now I've hit my roadblock though with something I've never done and that's to take the time that's been inserted into my table, select it if the time is less than five minutes and utilize it for my online users section
public function OnlineUsers() {
$query = <<<SQL
SELECT userid
FROM {$this->tprefix}online
WHERE timestamp > time(5Minutes)
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute();
$this->onlinecount = $resource->rowCount();
if($resource->rowCount() == 0 ) {
$this->onlineusers = "No User's Online";
}
else
{
foreach($resource as $row) {
self::ConvertIDToName("displayname"); //Can be display, user, first or whatever else for the argument, The onlineusers variable is then set based off that query
}
}
}
$minutes = 5;
$date = gmdate('Y-m-d H:i:s'); // http://php.net/manual/en/function.gmdate.php
$date_plus_minutes = gmdate('Y-m-d H:i:s', ( time() + $minutes * 60 ) );
$date_minus_minutes = gmdate('Y-m-d H:i:s', ( time() - $minutes * 60 ) );

Youtube playlist all videos duration show in php

i want to equal youtube playlist all videos time from this link http://gdata.youtube.com/feeds/api/playlists/PLCK7NnIZXn7gGU5wDy9iKOK6T2fwtGL6l. here have time code like this time='00:05:11.500' .. i want to get all videos time from php then its show like this from php
show it like this : 2:10:50 (2=hours,10=minutes,50=seconds)
i want to variable from php for like this one. plzz help for this post thanks. i tried to do that.. but i can do this.. if someone can plz help me.. if have 4 videos, want to equal all videos time and then want to show all duration from php only
Ok, here's an answer that solves the problem assuming you have no code whatsoever, and no intention of
trying do experiment yourself.
You will probably not be able to use this for anything else than the exact problem described:
adding all the durations of this feed together and displaying it as hours:minutes:seconds
<?php
$total_seconds = 0;
$dom = new DOMDocument();
$dom->loadXML(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/PLCK7NnIZXn7gGU5wDy9iKOK6T2fwtGL6l'));
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//yt:duration/#seconds') as $duration) {
$total_seconds += (int) $duration->value;
}
Then you display $total_seconds in your format. Here's two options:
assuming that hours will never be larger than 24
echo gmdate("H:i:s", $total_seconds);
allowing total time to be larger than 24 hours
echo (int) ($total_seconds / 3600) . ':' . (int) ($total_seconds / 60) % 60 . ':' . $total_seconds % 60;
Keep in mind: This code does exactly ZERO error checking. Things that can go wrong:
The PHP configuration may not allow http stream wrapper
The PHP build might not have Dom enabled
The XML feed may be unavailable
The XML feed might not contain any entries
EDIT:
I took a closer look at the feed, and it seems the "time" entries are just pointers for the thumbnails. The actual duration for a video is set in seconds <yt:duration seconds='667'/> so you could just add them together as integers and then use the DateTime class to convert to whatever your format is. Example here.
END EDIT
First of all, to get all the times, you could need an atom feed reader in PHP. There are plenty out there. Do not try to parse the XML, ATOM is a well known standard that should be easily used (if you really only want the times, you could go with an xpath query).
Now that you have all the times at your disposal, you need a way to add them up easily, preferably without messing with nested loops and if-statements.
Here's a class that represents a single time entry for a single video:
final class Duration
{
private $hours;
private $minutes;
private $seconds;
private $centis;
/* we don't want any Durations not created with a create function */
private function __construct() {}
public static function fromString($input = '00:00:00.000') {
$values = self::valuesFromString($input);
return self::fromValues($values['hours'], $values['minutes'], $values['seconds'], $values['centis']);
}
public function addString($string) {
$duration = self::fromString($string);
return $this->addDuration($duration);
}
public function addDuration(Duration $duration) {
// add the durations, and return a new duration;
$values = self::valuesFromString((string) $duration);
// adding logic here
$centis = $values['centis'] + $this->centis;
$this->fixValue($centis, 1000, $values['seconds']);
$seconds = $values['seconds'] + $this->seconds;
$this->fixValue($seconds, 60, $values['minutes']);
$minutes = $values['minutes'] + $this->minutes;
$this->fixValue($minutes, 60, $values['hours']);
$hours = $values['hours'] + $this->hours;
return self::fromValues($hours, $minutes, $seconds, $centis);
}
public function __toString() {
return str_pad($this->hours,2,'0',STR_PAD_LEFT) . ':'
. str_pad($this->minutes,2,'0',STR_PAD_LEFT) . ':'
. str_pad($this->seconds,2,'0',STR_PAD_LEFT) . '.'
. str_pad($this->centis,3,'0',STR_PAD_LEFT);
}
public function toValues() {
return self::valuesFromString($this);
}
private static function valuesFromString($input) {
if (1 !== preg_match('/(?<hours>[0-9]{2}):(?<minutes>([0-5]{1}[0-9]{1})):(?<seconds>[0-5]{1}[0-9]{1}).(?<centis>[0-9]{3})/', $input, $matches)) {
throw new InvalidArgumentException('Invalid input string (should be 01:00:00.000): ' . $input);
}
return array(
'hours' => (int) $matches['hours'],
'minutes' => (int) $matches['minutes'],
'seconds' => (int) $matches['seconds'],
'centis' => (int) $matches['centis']
);
}
private static function fromValues($hours = 0, $minutes = 0, $seconds = 0, $centis = 0) {
$duration = new Duration();
$duration->hours = $hours;
$duration->minutes = $minutes;
$duration->seconds = $seconds;
$duration->centis = $centis;
return $duration;
}
private function fixValue(&$input, $max, &$nextUp) {
if ($input >= $max) {
$input -= $max;
$nextUp += 1;
}
}
}
You can create a new Duration only by calling the static factory fromString(), and that accepts only strings in the form "00:00:00.000" (hours:minutes:seconds.milliseconds):
$duration = Duration::fromString('00:04:16.250');
Next, you can add another string or an actual duration object, to create a new Duration:
$newDuration = $duration->addString('00:04:16.250');
$newDuration = $duration->addDuration($duration);
The Duration object will output it's own duration string in the format '00:00:00.000':
echo $duration;
// Gives
00:04:16.250
Or, if you're interested in the separate values, you can get them like so:
print_r($duration->toValues());
// Gives
Array
(
[hours] => 0
[minutes] => 4
[seconds] => 16
[milliseconds] => 250
)
Final example for using this in a loop to get the total video time:
$allTimes = array(
'00:30:05:250',
'01:24:38:250',
'00:07:01:750'
);
$d = Duration::fromString();
foreach ($allTimes as $time) {
$d = $d->addString($time);
}
echo $d . "\n";
print_r($d->toValues());
// Gives
02:01:45.250
Array
(
[hours] => 2
[minutes] => 1
[seconds] => 45
[milliseconds] => 250
)
For questions on why I used a final class with private constructor:
I wrote this as an exercise for myself, following Mathias Veraes's blog post on "named constructors".
Also, I couldn't resist adding his "TestFrameworkInATweet" as well:
function it($m,$p){echo ($p?'✔︎':'✘')." It $m\n"; if(!$p){$GLOBALS['f']=1;}}function done(){if(#$GLOBALS['f'])die(1);}
function throws($exp,Closure $cb){try{$cb();}catch(Exception $e){return $e instanceof $exp;}return false;}
it('should be an empty duration from string', Duration::fromString() == '00:00:00.000');
it('should throw an exception with invalid input string', throws("InvalidArgumentException", function () { Duration::fromString('invalid'); }));
it('should throw an exception with invalid seconds input string', throws("InvalidArgumentException", function () { Duration::fromString('00:00:61:000'); }));
it('should throw an exception with invalid minutes input string', throws("InvalidArgumentException", function () { Duration::fromString('00:61:00:000'); }));
it('should add milliseconds to seconds', Duration::fromString('00:00:00.999')->addString('00:00:00.002') == Duration::fromString('00:00:01.001'));
it('should add seconds to minutes', Duration::fromString('00:00:59.000')->addString('00:00:02.000') == Duration::fromString('00:01:01.000'));
it('should add minutes to hours', Duration::fromString('00:59:00.000')->addString('00:02:00.000') == Duration::fromString('01:01:00.000'));
it('should add all levels up', Duration::fromString('00:59:59.999')->addString('00:01:01.002') == Duration::fromString('01:01:01.001'));
$duration = Duration::fromString('00:00:01.500');
it('should add a Duration', $duration->addDuration($duration) == '00:00:03.000');

Session Timeout in codeigniter dyanamicly

I have issue regarding codeigniter Timeout .
I know the config folder setting session timeout manually like as l
$config['sess_expiration'] = 123;
but i need to the website admin manage the session time out dyanamicly in to the admin page
please help me how to implement this logic
i tried this logic but not working
$this->session->sess_expiration = "120";
Note:here i am storing database in the value. based on the database value i can set in to the session expiration time
note 1: $config['sess_time_to_update'] = 30; this value less than of session expiration time
Total Logic code:
public function edit($id)
{
Assets::add_css('../plugins/forms/uniform/uniform.default.css');
Assets::add_css('../plugins/forms/select/select2.css');
Assets::add_css('../plugins/forms/validate/validate.css');
Assets::add_css('../plugins/misc/qtip/jquery.qtip.css');
Assets::add_js('../plugins/charts/sparkline/jquery.sparkline.min.js');
Assets::add_js('../plugins/forms/uniform/jquery.uniform.min.js');
Assets::add_js('../plugins/forms/select/select2.min.js');
Assets::add_js('../plugins/forms/validate/jquery.validate.min.js');
Assets::add_js('../plugins/forms/wizard/jquery.bbq.js');
Assets::add_js('../plugins/forms/wizard/jquery.form.js');
Assets::add_js('../plugins/forms/wizard/jquery.form.wizard.js');
Assets::add_module_js('setting','setting');
if ($_POST)
{
$current_date = date("Y-m-d H:i:s");
$data = array(
's_meta_value' => $this->input->post('s_meta_value'),
'updated_on' => $current_date
);
$this->setting_model->session_mng_update($data,$id);
$session_val= $this->input->post('s_meta_value');
if($session_val == 0)
{
$this->session->sess_expiration = '0';
}
else
{
$this->session->sess_expiration = "120";
// $val1 = $this->config->item('sess_expiration');
// print_r($val1);
//$session_seconds = ($session_val*60);
$val2 = $this->config->set_item('sess_expiration',50);
$this->session->CI_Session();
//$val1= $this->config->set_item('sess_expiration',50);
$val3 = $this->config->item('sess_expiration');
print_r($val3);exit;
}
Template::redirect('setting/setting/display');
}
$val3 = $this->config->item('sess_expiration');
print_r($val3);exit;
$data = $this->setting_model->session_mng_edit($id);
Template::set('page_title', 'Edit Session Management');
Template::set('data', $data);
Template::set_view('setting/session_management/edit_session_management');
Template::render();
}
First of all you could set cookies for this process via $this->input->set_cookie(). But if you want to overwrite the config variable then try
$this->config->set_item('sess_expiration',120);
Also call the session constructor to update the value by
$this->session->CI_Session();
You should use something like this:
$remember_me = $this->input->post('remember_me');
if ($remember_me == 'remember_me')
{
//set session to non-expiring
$this->session->sess_expiration = '32140800'; //~ one year
$this->session->sess_expire_on_close = 'false';
#$this->session->set_userdata($session_data);
}
else
{
//set session expire time, after that user should login again
$this->session->sess_expiration = '1800'; //30 Minutes
$this->session->sess_expire_on_close = 'true';
#$this->session->set_userdata($session_data);
}
//set session and go to Dashboard or Admin Page
$this->session->set_userdata(array(
'id' => $result[0]['id'],
'username' => $result[0]['username']
));

PHP if based on current system date

Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg

Categories