I'm using CodeIgniter, I want to offer discount for limited period of time. I don't know how to code it, would sessions be okay? But what if I want it only for first 15 mins, how can I manage that?
You can try something like this:
You might have to change your logic slightly to make this work.
<?php
function discount_period($field,$time)
{
$t = time();
$t0 = $_SESSION[$field];
$diff = $t - $t0;
if ($time > 1500 || !isset($t0))
{
return true;
}
else
{
$_SESSION[$field] = time();
}
}
/* Inside your header */
if(discount_period("user_time",1500))
{
session_unset();
session_destroy();
location("some-other-page.php");
exit;
}
?>
I don't know how you gonna do it but you can use this snippet of code as a reference.
<?php
$userLoggedInDate = new DateTime('now'); //The time user logged in. You can store it in the session variable the first time the user had logged in.
$promoDate = 'April 26, 2014';
$date = new DateTime($promoDate); //promo start date
$date2 = new DateTime($promoDate.'+15 min'); //add 15 mins to the date
var_dump($userLoggedInDate>$date2); //is logged in date greater than the promo end time?
var_dump($userLoggedInDate<$date2); //is logged in date less than the promo end time?
Related
I tried to substract 15 min. from another time (start-time).
I want to check if the current time is 15 min. befor a meeting starts.
foreach($result->value as & $value) {
$start = $value->Start->DateTime;
$startmeeting = substr($start, 11, -11); //cut time to hour:minute
$now= date('H:i', time());
$min= strtotime('-15 minutes');
$timebefor = date($startmeeting, $min); //Here I want to substract starttime with 15 min
if( $now >= $timebefor && $now <= $startmeeting )
{
//Show yellow warning box
}
}
Is it even possible on this way?
You basically have your solution, but it is untidy, and contains bugs. I think you want to do something like this:
foreach ($result->value as $value) {
$meetingStart = strtotime($value->Start->DateTime);
if (($meetingStart > time()) &&
($meetingStart < strtotime('15 minutes')))
{
//Show yellow warning box
}
}
Simply put: If the meeting is in the future, but less than 15 minutes into the future, you will have to show the yellow warning box.
When programming always pay attention to the names you choose. Notice how I use $nowPlus15Minutes which does clearly indicate what that variable contains. You used $min which isn't very self explanatory. The same problem exists with names like $value and $start. Perhaps $timebefor is a misspelling?
I recommend that you use PHP:DateTime with this. If your system works with external API (such as Google Calendar), I will usually specify the timezone too.
$currentTime = new DateTime("now", new DateTimeZone("Asia/Singapore"));
$reminderTime = new DateTime("2019-08-08T12:00:00.0000000", new DateTimeZone("Asia/Singapore"));
$reminderTime->sub(new DateInterval("PT15M")); // PT means period time, 15 minutes.
// Comparison of DateTime is allowed from PHP 5.2.2 onwards
if($currentTime > $reminderTime) {
// Do something
}
// For DEBUGGING
echo $currentTime->format('Y-m-d H:i:s') . "\n" . $reminderTime->format('Y-m-d
H:i:s');
Refer to DateTime documentation for more information.
Hi guys i have a code that start and end in specific time, my code is work fine but i want to use this code in data that loop
for example i'll pot names in loop and i want for each one to start and end in specific time:
this is my code:
<?php
date_default_timezone_set('America/New_York');
$time = date('Y:m:d H:i:s');
$timestart = date('Y:m:d H:i:s'); //time start
$timeend = '2016:11:17 10:56:00'; //time end
if($time >= $timeend){
echo "time end";
}else{
echo 'untel end time';
}
$now = new DateTime();
$future_date = new DateTime($timeend);
$interval = $future_date->diff($now);
?>
and i want to know how to use it with loop data?
thanks.
You can use EV or Event extension or implement by loop. I prefer EV extension to this task
And create timer for example:
// Required create variable!
$w = new EvTimer($needWorkedSeconds, $repeatAfterSecond, function ($w) {
echo "iteration = ", Ev::iteration(), PHP_EOL;
});
// Loop until Ev::stop() is called or all of watchers stop
Ev::run();
More read here!
OR use event (but i prefer event to work with socket):
$base = new \EventBase();
$e = \Event::timer($base, function($n) use (&$e) {
echo "$n seconds elapsed\n";
if($isTimeEndNow)
{
$e->delTimer();
}
}, $repeatAfterSecond);
$e->addTimer($repeatAfterSecond);
$base->loop();
More read here!
Or you can try while, for example:
while(true)
{
if($isTimeEndNow)
{
break;
}
sleep($repeatAfterSecond);
}
In example i use undeclareted variable:
$repeatAfterSecond - seconds to next iteration or next call
$isTimeEndNow - this is: time() > $endTimestamp
$needWorkedSeconds - this is seconds: time_start - time_end
ATTENTIONAL!!! Be Careful! I think you make mistake, if you want use MySQL and if you need die script in concrete time. Review your algorithm!!!
In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}
i need a script that automatically add a random number (between 1 and 5) every 24 hours and stores it in a text file, then after 24 hours creates a new random number and adds it to the previous result in the text file, i managed to do something close but still needs a refresh button to take effect, but i want it to automatically do it, so if 1 user visits the page every day, and one visits the page once a month, they should both see the same number (which will be read from the text file).
Here is my code so far:
<?php
$dataFile = "amt.txt";
$date1 = date("H:i:s");
$date2 = date("H:i:s",filemtime("amt.txt"));
$diff = abs(strtotime($date2) - strtotime($date1));
$secs = floor($diff);
if ($diff < 86400) {
echo "$date1 \n";
echo "$date2 \n";
printf($secs);
exit;
}
if (!file_exists($dataFile)) {
$amt = 0;
}
else {
// Otherwise read the previous value from
// the file.
$amt = (int) file_get_contents($dataFile);
}
// Generate the new value...
$Number = rand(1,5);
$total = $amt + $Number;
echo "$". $total ."/-";
// And dump it back into the file.
if (!file_put_contents($dataFile, $total)) {
// If it fails to write to the fle, you'll
// want to know about it...
echo "Failed to save the new total!";
}
?>
basically i want to show a fake number of subscribers which logically should increase with time. So i want to update the number on daily basis, then because i am having this on my website as the number of monthly subscribers, so when a user visits the website any time should see the same figure as any other user visitng the website on that exact time. Hope this is clearer now.
I'd first use time() instead date(xxx) so you get the diff secodns directly. But i don't get the purpose of this and don't know if you want to append the numbers or overwrite them, and also if the number changes every 24h why a user a month later should get the same number.
$date1 = time();
$date2 = filemtime("amt.txt");
$diff = $date1 - $date2;
if ($diff < 86400)
{
echo "$date1 \n";
echo "$date2 \n";
printf($diff);
exit;
}
This is the flow of commands on my login page
User loads page
php checks if the ip address is in the db, if not it adds it
php checks in the ip address is blocked in the db, if not it proceeds
if it is blocked the script will proceed to get the time the ip was blocked at from the db and calculate the amount of time left until the user can try to login again. The blockout time is 15minutes.
However the problem is that if the user was blocked at 45-59 minutes past the hour then 45+15= 00(as 60 doesn't come up on the time) and any number between 45 and 60 excluding 45 and 60 will go past the hour so for example if i get blocked out at 11:48 i will be unblocked at 12:03.
The problem, if you haven't already figured out is how do i code the countdown timer so it goes past the hour and doesn't spazz out when it goes past 59minutes.
Also i want to do this in php as i have no need to actually present the time left in real-time.
The current minute is never an issue. You are concerned with the duration since last blocked, not with "what time was that":
block_user.php:
<?php
$now = new DateTime();
write_block_into_database($ip_address, $now->format('Y-m-d H:i:s'));
?>
check_block.php
<?php
$sql = 'SELECT 1 FROM sometable WHERE ip_address=? AND DATE_ADD(blocked_at, INTERVAL 1 HOURS) >= NOW()';
if(get_result($sql, $ip_address)) {
// this address is blocked
} else {
// no recent block found
}
Or, if you want to do the comparison in PHP:
check_locally.php:
<?php
$sql = "SELECT blocked_at FROM sometable WHERE ip_address=?";
$db_row = get_row($sql,$ip_address);
if ($db_row) {
$blocked = new DateTime($db_row->blocked_at);
$blocked->modify('+1 hour');
$now = new DateTime();
if ($blocked >= $now) {
// still blocked
} else {
// was blocked earlier, no more
}
} else {
// not blocked
}
In other words: "if I take the time the IP was blocked and add one hour, is now still before that point in time?"
Example:
blocked at 12:48
checking at 13:10: 12:48 + 1 hour = 13:48, 13:48 >= 13:10, fail
checking at 15:10: 12:48 + 1 hour = 13:48, 13:48 < 15:10, pass
This is what I managed to come up with
$date = new DateTime();
$currentTime = $date->getTimestamp();
$blockTime = "1453494620";//This value will be taken from the mysql db
$timeElapsed = $currentTime - $blockTime;
echo "Current Time: $currentTime";
echo "<br>Block Time: $blockTime <br>";
if ($timeElapsed < 900){
$leftTime = ((900 - $timeElapsed) / 60) + 1;
$DotPosition = (stripos($leftTime, ".")) + 1;
if($DotPosition == 3 || $DotPosition == 2){
$leftTime = substr($leftTime, 0, $DotPosition - 1);
}
if($leftTime == 1){
$minutesString = "minute";
} else $minutesString = "minutes";
echo "<br>You are blocked from trying to login for too many incorrect tries.
<br>Please try again in $leftTime $minutesString.";
} else {
/*for test purpose, here the user will get unblocked on the mysql by updating the
ips blockout field */
echo "<br>You have been unblocked.";
}
Current Time: 1453495488
Block Time: 1453494620
You are blocked from trying to login for too many incorrect tries.
Please try again in 1 minute.
Thank you guys for telling me about UNIX Timestamps. If I knew about them I wouldn't have asked. :)