Comparing Two Time stamps in PHP - php

I am trying to prevent spam in my contact form. When anyone contact using contact form, I am saving his IP Address in Database with Current Time. If someone try contact, I am checking IP in database and if there IP address entry in Database, I am getting timestamp of it and comparing it with current timestamp but I think there something wrong with it and its giving me wrong time and so user are still able to send messages.
I have defined TimeZone like below
define('TIMEZONE', 'Asia/Kolkata');
date_default_timezone_set(TIMEZONE);
$date = date('Y/m/d h:i:s', time());
I am inserting write time in database same as echo in php.
Now I am getting and comparing both time like below
$last_time = $row['time'];
$current_time = $date;
if(($current_time-strtotime($last_time )) > 1800) {
//send mail
}
else {
// give error
}
I have tried echo both time and I am getting result like this
$last_time = 2018-09-23 07:56:37
$current_time = 2018/09/23 07:56:51
($current_time-strtotime($last_time ) = -1537667579
I don't know whats wrong with it.
Let me know if there anything wrong with it.

Also convert the current time into strtotime. Make sure both date format should be same
define('TIMEZONE', 'Asia/Kolkata');
date_default_timezone_set(TIMEZONE);
$date = date('Y/m/d h:i:s', time());
$last_time = $row['time'];
$current_time = $date;
if((strtotime($current_time)-strtotime($last_time )) > 1800) {
//send mail
}
else {
// give error
}

Related

PHP date function giving a random number

Hello i'm making a php script to send an email on a client's birthday, basicly i'm looping through every client's birthdates and checking with today's date and if they match, an email is sent. Although the date function is giving a random number instead of today's date, the number is: 1505451600.
Maybe i'm doing something wrong in the code? Does anyone know a way to fix this?
$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
// echo "</br> data:".$array_birthday['dt_nascimento'];
// echo "</br>".$birthdate;
$now = date("m/d");
$now = strtotime($now);
// echo "</br>now: ".$now;
$email = $array_birthday['email'];
if ($now == $birthdate) {
include"PHPMailer/email_birthday.php";
}
}
}
There are 2 changes you need to make for your code to work:
(1) Remove this line:
$now = strtotime($now);
Reason: You don't want a timestamp. You want a formatted date.
(2) Change "m d" on this line:
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
to "m/d" like so:
$birthdate = date('m/d', strtotime($array_birthday['dt_nascimento']));
Reason: you need to format $birthdate and $now the same way to make the comparison work.
I remove the $now conversion to timestamp and change the $birthdate format to the same as $now.
This is the working code :
$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
// echo "</br> data:".$array_birthday['dt_nascimento'];
// echo "</br>".$birthdate;
$now = date("m d");
// echo "</br>now: ".$now;
$email = $array_birthday['email'];
if ($now == $birthdate) {
include"PHPMailer/email_birthday.php";
}
}
}
The reason it gives you a number is how computers measure time is the number of seconds since 1/1/1970 00:00 (UTC (Universal Time)).
1505451600 Is equivalent to: 09/15/2017 # 5:00am (UTC)
this happens because:
date("m/d") returns 9/15 (today month/day)
then strtotime tries to convert this string into unix timestamp, as soon as year is not in string, current year (2017) is assumed
as soon as time part is not there, midnight in your timezone is assumed (5am utc)
this is why final time is 1505451600

PHP DateTime() function not working properly

I have an Android app which is used to store data of users in MySQL database using PHP. I need to do some validations according to the date.The MySQL Database has a predefined date for each user.The date increases by 1 day whenever a user inserts data twice for that day.And when the date exceeds the current date,it shows a message that "the user has already submitted data for the day".
My PHP file is :
<?php
require "conn.php";
$user_mobile = $_POST["mobile_num"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee_data where mobile like '$user_mobile' and password like '$user_pass';";
$result = mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result) > 0 ) {
$row = mysqli_fetch_assoc($result);
$name= $row["name"];
$_POST['user'] = $name;
$last_updated = $row["last_updated_date"];
$_POST['user'] = $name;
$_POST['date'] = $last_updated;
echo "Login successful. Welcome_" .$name;
echo "_Date:" .$last_updated;
$now = new DateTime("Asia/Kolkata");
$n = ($now->format('Y-m-d'));
if(($last_updated > $n)) {
echo "exceeded";
}
?>
But what is happening is if "$last_updated"(the date which is changing everytime) is the current date,then it is not going inside the if condition. So if "$last_updated" is today's date, then the user gets the message "the user has already submitted data for the day". I tried doing an echo of "$n" and it gives the current date. So, it should not go to the if-condition because ($last_updated == $n) . But its going inside the if-condition when ($last_updated == $n).I don't know why this is happening.Can anyone please help me with this?
Try to change your
$now = new DateTime("Asia/Kolkata");
to:
$now = new DateTime(null, new DateTimeZone('Asia/Kolkata'));
You need to compare them as objects.. Try something like this..
$now = new DateTime("Asia/Kolkata");
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
I'm not sure if your timezones are set properly on your server but to be sure you could do one of the following as well..
$now = new DateTime('Asia/Kolkata');
if (new DateTime($last_updated, new DateTimeZone('Asia/Kolkata')) > $now) {
echo "exceeded";
}
Or probably even better..
date_default_timezone_set('Asia/Kolkata');
$now = new DateTime('now');
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
Your issue is that since you are not keeping the time in the database and when you compare the date with now which includes the time, the now will always be greater than the date you pull from the database.
The database time 2017-03-17 becomes 2017-03-17 00:00:00 php time.
When you generate php now time it will be 2017-03-17 xx:xx:xx which will always be greater than database time
$last_updated = new DateTime($row["last_updated_date"],new DateTimeZone("Asia/Kolkata"));
$today = new DateTime('now',new DateTimeZone("Asia/Kolkata")); //gets current date time
$today->setTime(0,0); // back to the beginning of the day
//echo $last_updated->getTimestamp . | . $today->getTimestamp; // for debugging purpose
if(($last_updated->getTimestamp >= $today->getTimestamp)) {
// note that I have used '>=' to allow the current date
}
You can also use the DateTime->diff() function.
Reference: http://php.net/manual/en/class.datetime.php

Comparing two dates in PHP and MYSQL

I want to compare two dates and time values in PHP. One date is coming from MySQL, and second one is the current date. I want to run some code when both dates are the same. I tried the code below, but condition satisfies any time which is wrong.
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
}else{
}
What is wrong with the code? I also tried to covert both dates with strtotime() before comparing, but it gave me the same issue. The above condition satisfies any time even if both dates are different.
Try this :
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if(strtotime($current_datetime) == strtotime($send_date)){
//I want to run some code here
}else{
}
Hope it helps !!!!
One way is to fetch the Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) from MySQL, then operate on the numbers:
$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
// current hour
}
Timestamps are convenient because:
there is no need to take the format into account;
operations on numbers are usually faster;
the code looks cleaner.
Try this. On my server is working just great I've got something else because they aren't equal. Date which I receive from database is type datetime format 2015-04-13 09:03:49
<?php
$current_datetime = strtotime(date('Y-m-d H:i'));
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
echo 'something';
}else{
echo 'something else';
}
Output:
echo $current_datetime . '<br/>';
2016-10-17 09:19
echo $send_date .'<br/>';
2015-04-13 09:03
// result
something else

Comparing a date to current server date using PHP

I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);

Dealing with Timezones and Dates in PHP

I am running a service hosted on a server in the US which reads an XML feed that has been created with a local date - currently just the UK, but I want to ensure the service works with all timezones.
My process looks at the date of a post in a feed and compares it with the date/time right now(on the server in the US).
The solution I came up with localises the system to the originator of the feed and then creates a timestamp with which to compare 'now' with:
protected function datemath($thedate){
$currenttimezone = date_default_timezone_get();
date_default_timezone_set($this->feedtimezone);
$thedate = mktime substr($thedate,11,2),substr($thedate,14,2),
substr($thedate,17,2),substr($thedate,3,2),substr($thedate,0,2),
substr($thedate,6,4));
date_default_timezone_set($currenttimezone);
return $thedate;
}
My question is this... Is this a reasonable way of handling this issue or is there a better, more standardized way that I really should know?
Here's a function I wrote to do timezone conversions. Should be pretty self-explanatory:
function switch_timezone($format, $time = null,
$to = "America/Los_Angeles", $from = "America/Los_Angeles")
{
if ($time == null) $time = time();
$from_tz = new DateTimeZone($from);
$to_tz = new DateTimeZone($to);
if (is_int($time)) $time = '#' . $time;
$dt = date_create($time, $from_tz);
if ($dt)
{
$dt->setTimezone($to_tz);
return $dt->format($format);
}
return date($format, $time);
}
After a bit more checking of other peoples code I see the function
strtotime($thedate);
is a little bit more succinct than using mktime and also allows for different time formats.

Categories