Time, and if statement - php

I'm attempting to check if a time is past the given time on the locked account. I have attempted several ways and the problem is consistent. Any help is appreciated. The format of the sql entry is the same as $datetime in the variable, except the datetime in the database is set to +30 minutes from the time it was locked. The problem is that it is ALWAYS returning the variable as 1, unless it's flipped to say $datetime >= $row['locked'] then it always returns 0. What I want to happen is if the time is within thirty minutes it returns 1, if not then 0.
First
function anotherMethod($userclean)
{
if($this->isLocked($userclean) == 1)
{
header('Location: login.php?i=l');
die();
}
}
Second
function isLocked($userclean)
{
$datetime = date('m-d-Y h:i:s');
$results = mysqli_query($this->con, "SELECT * FROM users WHERE username = '".$userclean."'");
while($row = mysqli_fetch_array($results))
{
$str = $row['locked'];
}
if ($datetime >= $row['locked']){
$islocked = 1;
}else{
$islocked = 0;
}
return $islocked;
}

Related

Extract only the number of the day of the date and compare it with the current one

I need to extract only the day number of a user's registration date.
And extract only the day number of the current date.
Simply in an if loop, say if the day number the user registered is equal to the day number of the current date, do this, or do that.
Code:
$manager = "Manager";
$managerPRO = "ManagerPRO";
$q = $connessione->prepare("
SELECT * FROM collaboratori
WHERE cat_professionisti = ?
OR cat_professionisti = ?
");
$q->bind_param('ss', $manager,$managerPRO);
$q->execute();
$r = $q->get_result();
while($rr = mysqli_fetch_assoc($r)){
/*REGISTRATION DATE*/
$registrazione = $rr['data_registrazione'];
$timestamp = strtotime($registrazione);
echo date("d", $timestamp) .'=' ;
/*CURRENT DATE*/
$data_corrente = date('Y-m-d');
$timestamp_uno = strtotime($data_corrente);
echo date("d", $timestamp_uno);
/*CONTROL*/
if ($timestamp == $timestamp_uno){
echo "yes".'<br>';
}else{
echo "no".'<br>';
}
}
Result:
18=18no
17=18no
16=18no
16=18no
Why in the first case if 18 = 18 gives me false?
However, if I change the date of the user's registration and therefore the first 18, from 2020/11/18 to 2020/12/18, then the current month gives me yes!
I need that regardless of the month, just by checking the day if it is the same, tell me yes, where am I wrong?
You are comparing timestamps, which are measured in seconds. What you are doing is effectively comparing two different points in time, not the days of the month.
You really should be using DateTime. If you want to compare only the day part then you can do something like this.
$dt1 = new DateTime($registrazione);
$dt2 = new DateTime(); // defaults to now
if($dt1->format('d') === $dt2->format('d')) {
echo "Yes, it's the same day of the month";
} else {
echo 'no!';
}

How to show leave expiry date of an employee

First I count the number of days between leave dates and resume date e.g. From 26–July-2019 To 31-July-2019 is 5 days. Then I need to know the number of days counting from the leave date to the current date and store in a variable named $count_days. if the no of leave days minus count_days is equal zero then I would say your leave has expired.
I could not figure it out how to get it right
<?php
// include the file that defines (contains) the username and password
require_once("includes/mysqlconn.php");
// build qry
$qry = "SELECT employee.emp_num,employee.emp_lname,employee.emp_fname,eleave.leave_date,eleave.resume_date from employee INNER JOIN eleave ON employee.emp_num = eleave.emp_num where employee.emp_num = '".$_SESSION['empno']."'";
$records = mysqli_query($dbconn,$qry) or die('Query failed: ' . mysqli_error($dbconn));
$time_current = time();
while ($line = mysqli_fetch_array($records))
{
$leavedate = strtotime($line['leave_date']);
$resume_date = strtotime($line['resume_date']);
//count days between dates to get no of leave days
$leave_days = ceil(abs($resume_date - $leavedate) / 86400);
//this is to get days difference between no of leave days and the current day
//when echo $count_days give me -1564264800 I don't know what this value stand for
$count_days = $leavedate - strtotime($time_current);
if (($leave_days-$count_days) <> 0){
echo "enjoy your leave";
}else{
echo "your leave has expired";
}
}
mysqli_close($dbconn);
?>
First of all, $time_current is already in 'time' (integer) format, so strtotime($time_current) is probably NOT what you want to do. Second, if you are checking whether resume_time has passed (aka their leave is over), all you have to do is:
if( $time_current < $leave_time ){
echo 'your leave has not started';
}elseif( $time_current > $resume_time ){
echo 'your leave has expired';
}else{
echo 'enjoy your leave';
}
Otherwise, if you want to know the number of days between, correctly subtract (already integer) $time_current and $resume_date and divide by 86400. For the sake of ease (and understanding) I have wrapped this into a function for you:
function numDaysBetweenTimes(int $time1, int $time2 = null) : int{
if( !$time2 ){
$time2 = time();
}
return ceil(abs($time1 - $time2) / 86400);
}
Example usage:
$line['leave_date'] = '2019-01-15 00:00:00';
$line['resume_date'] = '2019-01-05 00:00:00';
$time_current = time();
$leaveTime = strtotime($line['leave_date']);
$resumeTime = strtotime($line['resume_date']);
echo numDaysBetweenTimes($leaveTime, $resumeTime) . ' leave days<br/>';
echo numDaysBetweenTimes($resumeTime) . ' days between leave and now<br/>';
Output:
4 leave days
202 days between leave and now

Issues comparing two dates in php

For some reason I am having difficulties comparing a previous date and current date. I have tried many different things, and tried to google my way to an answer but with no luck.
This is how my code is..
$phpdate = date("Y-m-d");
$sql = "SELECT lastDailyCollect FROM users WHERE steamid='".$_POST['steamid']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$lastDailyCollect = $row['lastDailyCollect'];
}
}
if ($lastDailyCollect == $phpdate) {
//give user error message
}elseif ($lastDailyCollect != $phpdate) {
//let user know it suceeded
}else {
//comparison error
}
I want to check if the user is able to collect a daily bonus. The last collection date of each user is stored in a mysql database, in a table called users.
It always goes to the comparison error.
Hope somebody can help.
What you can do to check if lastDailyCollect date was previous day by subtracting one day from the current date and storing it in $yesterday then matching if previous date is equal to lastDailyCollect date.
<?php
$date = date("Y-m-d"); //2017-05-12
$lastDailyCollect = "2017-05-11";
$yesterday = date('Y-m-d',strtotime($date . "-1 days")); //2017-05-11
if($lastDailyCollect == $yesterday) {
//give user error message
echo 'lastDailyCollect is equal to Previous day';
}
else
{
//let user know it suceeded
echo 'lastDailyCollect is not equal to previous day';
}
?>

Limiting users from executing a code more than once a week (not automatic)

I want my users to just have access to executing a script just once a week.
Please note that i don't want the code to be executed once a week 'automatically'.
I want the user to just be able to just execute the code (synchronously) once a week. In the scope, the script i am restricting users from accessing is a scan. thanks...
I tried this but it didn't work.
if (isset( $_POST['action'])) {
switch($_POST['action']){
$q = mysql_query("SELECT dateStop from `run` where userid = $userid");
$row = mysql_fetch_assoc($q) or die(mysql_error());
$timeDiff = time() - $row['dateStop'];
$timeDay = $timeDiff / (24 * 60 * 60);
if ($timeDiff <= 604800) {
echo "<script> alert('You can only scan once in a week. Try again in the next $timeDay day(s)'); </script>";
case "is_running": {
$res = $db->query("SELECT 1 FROM `" . SQL_PREFIX . "run` WHERE userid = $userid and ISNULL(dateStop)");
die(json_encode(array("running" => (mysql_num_rows($res) > 0))));
} else {.....}
Just do it with SQL.
Provide userid to the following SQL and it will let you know if the User is allowed to Scan or NOT.
SELECT IF(DATEDIFF(CURRENT_TIMESTAMP, dateStop) >= 7, 'yes', 'no') AS allowedToScan
FROM `run`
WHERE userid = 2
SQL Fiddle: http://sqlfiddle.com/#!9/b32db6/10
I wrote up a quick script which will do what you want edit it around so it works for you. Read the comments they explain what is being done. Any problems comments and will check it
/**
**YOU can use this function to get hold of the date a week from your current date.
**It does generally process most date formats eg. 10-12-2015, jan 28, 2015, timestamp...
**/
function processDate($val, $days)
{
$value = $val;
$dayToAdd = $days;
switch($value)
{
case is_numeric($value):
// time()
$value = strtotime('+'.$dayToAdd.' days', $value);
$value = date('d - m - Y', $value);
break;
default:
// days + Unix
$value = strtotime(str_replace(',', '', $value));
$value = strtotime('+'.$dayToAdd.' days',$value);
$value = date('d - m - Y', $value);
break;
}
return $value;
}
/**
**Presuming this checks if a button is clicked?
**/
if(isset($_POST['action']))
{
/**
**Im presuming this query gets hold of the last date when the script was run.
**I DID NOT TEST THIS SCRIPT WITH A DB i testing it by setting $row['dateStop'] = time();
**You will have to test with db.
**/
//delete $row['dateStop'] = time() AND UNCOMMENT YOUR QUERY TO TEST IT.
$row['dateStop'] = time();
/**
**UNCOMMENT YOUR QUERY AND TEST SCRIPT USING IT.
**/
//$q = mysql_query("SELECT dateStop from `run` where userid = $userid LIMIT 1");
//$row = mysql_fetch_assoc($q) or die(mysql_error());
/**LastDate = last date script was run, NewDate = a week after last date, timeDiff = how many days diffrence
**You can edit the function to get the format to be whatever you need. So if you want it to be like unix
**timestamp you will have to change date('d - m - Y', $value); INTO a correct format use http://php.net/manual/en/function.date.php
**/
$LastDate = processDate($row['dateStop'], 0);
$NewDate = processDate($row['dateStop'], 7);
$timeDiff = $NewDate-$LastDate;
/**
**Correct way to use a switch case to check if either the date is within a week or if it has been a week.
**/
switch ($timeDiff)
{
case $timeDiff == 7:
//code to be executed if it has been a week;
echo "it has been 7 days".$timeDiff;
break;
case $timeDiff > 7:
//code to be executed if it has been over a week;
echo "it has been over 7 days".$timeDiff;
break;
case $timeDiff<7:
//code to be executed if it has been less than a week;
echo "it has been less than 7 days".$timeDiff;
break;
default:
//A default script to run incase none of the cases match;
}
}

Php not reading date as <= to current date correctly

I have tried every combo I can think of / found and no matter what I do, my codet echos the message even if the account isn't locked out:
<?php
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
//The date in the database is 10/31/11
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date <= $l_date) {
header("location:documnet_editors/edit_weddingplanner.php?id=$id");
}
else {
echo 'Whoops! Were sorry your account has been locked to edits
because your event is less than 48 hours from now or your event has passed.
To make changes to your event please contact your DJ.';
}
?>
<?php
//Destroy Session for Lockout Date to prevent bypasses
unset($_SESSION['lockout_date']);
?>
If your $l_date is populated, and I don't think it is, if it is stored as MM/DD/YY, you'll want to use PHP's strtotime to convert it to a unix timestamp for quick comparison:
if( strtotime($db_date) >= time() )
{
// do something
}
I would suggest comparing timestamps instead of formatted dates:
<?php
$date_a = new DateTime();
$date_b = new DateTime('2000-10-20 00:10:20');
if ($date_a->getTimestamp() > $date_b->getTimestamp()) {
echo 1;
} else {
echo 0;
}
convert your dates to unixtime for more accurate comparison. Add this function to your code:
function unix_time($date){
$unix_date = str_replace("-","/",$date);
$unix_date = str_replace(".","/",$unix_date);
$unix_date = str_replace(" pm","",$unix_date);
$unix_date = str_replace(" am","",$unix_date);
$time = strtotime($unix_date);
return $time;
}
then convert the dates to unix:
$l_date = unix_time($_SESSION['lockout_date']);
$c_date = unix_time($_SESSION['current_date']);
or you can also get the date directly from the database:
$l_date = unix_time($info['date_in_database']);
compare the dates in unix format:
if ($c_date = $l_date) {
// your code here
}
this should work.

Categories