To get timestamps to be in the user's time period, I have set up a timezone conversion tool with PHP for my posting system. Basically the user sets their own timezone through a dropdown, and this is stored on the database as a PHP timezone - so if I select GMT, the value in the database would be Europe/London.
The idea is then to take this from the database and plug it into a timezone conversion piece of code, but this presently isn't converting anything at all. Can anyone see the problem?
doMessage.php
$date = date("Y-m-d G:i:s");
$user_tz = $result['time'];
$schedule_date = new DateTime($date, new DateTimeZone($user_tz) );
$schedule_date->setTimeZone(new DateTimeZone('UTC'));
$date = $schedule_date->format('Y-m-d H:i:s');
core/init.php
<?php
session_start();
$db = new PDO('this is all correct');
if(isset($_SESSION['id'])) {
$i = $_SESSION['id'];
$query = $db->prepare("SELECT * FROM users WHERE id=:i");
$query->bindParam(":i",$i);
$query->execute();
$result = $query->fetch();
$ver = $result["activated"];
if($ver == 0) {
echo "Please <a href='activate.php'>verify your account.</a>";
}
}
else {
echo "Please <a href='login.php'>log in.</a>";
$guest = True;
}
To get current date and time of GMT, just this is enough:
date_default_timezone_set('GMT');
$current_date = date("Y-m-d h:i:s A T")
echo $current_date;
This outputs 2013-12-30 5:30:20 AM GMT
Related
I'm having a challenge comparing the current date with a date set in a database table CF_PROCUREMENT with the column name TENDER_DEADLINE_PROC for verification code in a portal. The TENDER_DEADLINE_PROC field needs to be in comparison with the current time but what seems to be put into comparison is two current timestamps. I am new to PHP.
$sql = "SELECT * FROM CF_PROCUREMENT WHERE CASEFOLDERID = '$code'";
$result = sqlsrv_query($db,$sql);
if ($result) {
$rows = sqlsrv_has_rows($result);
if($rows==true){
$date = new DateTime($row['TENDER_DEADLINE_PROC']);
$date = $date ->format('d/m/Y H:i:s');
$now = new DateTime();
$now = $now ->format('d/m/Y');
if($date > $now){
$mail->Subject = 'PORTAL Deadline Alert';
$mail ->Body = '
<html>
<body>
<h1>Deadline has lapsed</h1>
</body>
</html>';
$mail->send();
}else{
$mail->Subject = 'PORTAL Email Verification';
$mail ->Body = '
<html>
<body>
<h1>VERIFICATION CODE</h1>
<h2>Code: <b>'.$otp_code.'</b>
</body>
</html>';
}
[https://i.stack.imgur.com/ZkPTT.png][1]
<?php
$email=$_SESSION['user'];
$con = new mysqli('localhost', 'root', '', 'sconnect');
$data="SELECT * FROM events WHERE email='$email';";
$resmy=mysqli_query($con,$data);
if ($data) {
while($row = mysqli_fetch_array($resmy)) {
$gid = $row['event_id'];
$gquery ="select * from events where event_id='$gid';";
$myresq = mysqli_query($con,$gquery);
$grow = mysqli_fetch_array($myresq);
echo "<tr><td>".$row['event_id']."</td><td>".$grow['gname']."</td>
<td>".$grow['location']."</td><td>".$grow['date']."</td>
<td>".$grow['timing_from']."</td><td>".$grow['timing_to']."</td>
<td>".$grow['venue_details']."</td><td>".$grow['participants']."</td>
</tr>";
}
} else {
echo"<tr><td>You have not created any events yet</td></tr>";
}
?>
In this code I wish to add a column to display an event is active/expired/upcoming. In the above table date, event start time and event end time is available.
You can create a variable inside your PHP code to get status based on your table date field. Check below code:
<?php
$email=$_SESSION['user'];
$con = new mysqli('localhost', 'root', '', 'sconnect');
$data="SELECT * FROM events WHERE email='$email';";
$resmy=mysqli_query($con,$data);
if ($data) {
while($row = mysqli_fetch_array($resmy)) {
$gid = $row['event_id'];
$gquery ="select * from events where event_id='$gid';";
$myresq = mysqli_query($con,$gquery);
$grow = mysqli_fetch_array($myresq);
if (strtotime(date('Y-m-d H:i:s')) > strtotime($grow['date_to'])) { // means current time is greater than event to time which makes it expired.
$eventStatus = 'Expired';
} else if (strtotime(date("Y-m-d H:i:s", strtotime('-24 hours'))) > strtotime($grow['date_from'])) { //means event will start with in next 24 hours.
$eventStatus = 'Upcoming';
} else if (strtotime(date('Y-m-d H:i:s')) > strtotime($grow['date_from']) && strtotime(date('Y-m-d H:i:s')) < strtotime($grow['date_to']) ) { //means current time is in between of date_from and date_to.
$eventStatus = 'Ongoing';
} else {
$eventStatus = 'Active';
}
echo "<tr><td>".$row['event_id']."</td><td>".$grow['gname']."</td>
<td>".$grow['location']."</td><td>".$grow['date']."</td>
<td>".$grow['timing_from']."</td><td>".$grow['timing_to']."</td>
<td>".$grow['venue_details']."</td><td>".$grow['participants']."</td>
<td>".$eventStatus."</td></tr>";
}
} else {
echo"<tr><td>You have not created any events yet</td></tr>";
}
?>
Hope it helps you.
<?php
function find_days($start_date, $end_date) {
$response = new stdClass();
try {
$sdate = new DateTime($start_date);
$edate = new DateTime($end_date);
$dateInterval = $edate->diff($sdate);
$response->status = true;
$response->result = $dateInterval;
return $response;
} catch (Exception $e) {
$response->status = false;
$response->result = 'Invalid Date Format';
return $response;
}
}
?>
Start Date: <input type="date" name="sdate" placeholder="start date" />
End Date: <input type="date" name="edate" placeholder="end date" />
<input type="submit" value="Find Days" />
<?php
if (isset($_POST['sdate']) && $_POST['sdate']) {
$start_date = $_POST['sdate'];
$end_date = $_POST['edate'];
//now call the function
$days_array = find_days($start_date, $end_date);
if ($days_array->status) {
echo " <input type='text' name='day'
value='.$days_array>result>days.' />";
$day = $_POST['day'];
$query = "INSERT into cart (date,edate,days)
VALUES('$start_date','$end_date','$day')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
} else {
echo $days_array->result;
}
}
My code is working perfectly. But the result is displayed only on the screen.
So I've tried to store the result by placing it in a textbox and then insert into the table in a usual way. But I got an error "Catchable fatal error: Object of class DateInterval could not be converted to string in C:\xampp\htdocs\date.php on line 45"
I don't know how to rectify this.. please help me solve this.
You have to convert it to a string using format:
<?php
$now = new DateTime();
$hour = new DateTime( "now +1hours +13minutes +22seconds" );
$diff = $now->diff( $hour );
echo $now->format('Y-m-d H:i:s');
echo "\n";
echo $hour->format('Y-m-d H:i:s');
echo "\n";
echo $diff->format('%H:%I:%S');
Output
2018-07-26 20:53:42
2018-07-26 22:07:04
01:13:22
my first time writing prepared statement
this code is checking your late in every 3 hours then inserting the time interval into db
date_default_timezone_set('Asia/Hong_Kong');
$now = new DateTime();
if ($now->format("H:i") > "22:00") {
$deadline = DateTime::createFromFormat("H:i", "22:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "19:00") {
$deadline = DateTime::createFromFormat("H:i", "19:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "16:00") {
$deadline = DateTime::createFromFormat("H:i", "16:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "13:00") {
$deadline = DateTime::createFromFormat("H:i", "13:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "10:00") {
$deadline = DateTime::createFromFormat("H:i", "10:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "07:00") {
$deadline = DateTime::createFromFormat("H:i", "07:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
}
$stmt = $conn->prepare("INSERT INTO time_in (e_id, login, late, date_in)
VALUES (?, ?, ?,CURRENT_TIMESTAMP)");
$stmt->bind_param("sss", $e_id, $login, $diff->format('%H:%i'));
$e_id = "id is unavailable"; // changing to $_POST in the future
$login = "1";
$status = $stmt->execute();
if(!$status) {
echo $stmt->error;
exit;
}
echo "success";
}
and im getting this
Notice: Only variables should be passed by reference
at this line $stmt->bind_param("sss", $e_id, $login, $diff->format('%H:%i'))
the code working perfectly but im getting that notice
please help
you must pass actual variables to bind_param, since $diff->format('%H:%i') is not a variable but rather the output of a function, it doesn't like that.
You will need to assign this to a variable first then pass it in. i.e
$diffFormat = $diff->format('%H:%i');
$stmt->bind_param("sss", $e_id, $login, $diffFormat);
I am using a simple script at the top of every page that will update a LastActive column in the database:
$username = $_SESSION['username'];
$userID = $_SESSION['user_id'];
if(isset($username, $userID)) {
if ($insert_stmt = $mysqli->prepare("UPDATE Users SET lastActive = DATE_ADD(Now(), interval 6 hour) WHERE username = ?")) {
$insert_stmt->bind_param('s', $username);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
$insert_stmt->close();
header('Location: ../headers/error.php?err=Failed Upload');
}
}
$insert_stmt->close();
}
I always want to keep performance and security in mind. Would this lead to poor performance in the future with 000's of connections?
How does using cookies (not that I know how) differ from a simple script like this?
Thanks
edit:
$username = $_SESSION['username'];
$userID = $_SESSION['user_id'];
$loginTime = $_SESSION['timestamp'];
date_default_timezone_set("Europe/London");
$now = new DateTime();
$diff=$now->diff($loginTime);
$minutes = $diff->format(%i);
if(isset($username, $userID) && $minutes> 30) {
$_SESSION['timestamp'] = $now;
$online = true;
}
Couple of suggestions:
You could do this via AJAX, so that the LastVisited is updated asynchronously after the user's page loads. That way, there won't be any impact to the page load time for the user.
If, for any reason, your SQL query fails, you should fail silently. Since recording Last Visited is not business critical, you should not redirect the user to an error page. Maybe just log an error, and set up an alert so if there are multiple failures, you get alerted and can take a look at it.
All that you made with cookies will be data supplied by your users, then you cannot trust it.
In other hand, if you work with cookies, all of them will travel in each request header.
You should do it in server side and yes, a database is not performant.
You can try to persist this information with something like Redis, a in-memory data structure store, used as database, cache and message broker.
I thought I'd post the way I got around this for any one else looking for a User Online type method. Of course this might have been done much better but works in my situation.
I am using both database entries and session to test if a user is online.
On user login I update a column in my users table with a Now() timestamp and add this to their session data.
At the top of each page I am running a script to check if the user is logged in and get their timestamp from session data. if this data is 45 minutes old, the script will update the table setting the lastActive column of my users table to Now();
<?php
include_once 'functions.php';
if(isset($_SESSION['username'], $_SESSION['user_id'], $_SESSION['lastActive'])) {
date_default_timezone_set("Europe/London");
$now = new DateTime();
$lastActive = $_SESSION['lastActive'];
$diff=$now->diff($lastActive);
$hours = $diff->format('%h');
$mins = $diff->format('%i');
$day = $diff->format('%d');
$month = $diff->format('%m');
$year = $diff->format('%y');
if($mins > 45 || $hours >= 1 || $day >= 1 || $month >= 1 || $year >= 1) {
$_SESSION['lastActive'] = $now;
set_last_active($mysqli, $_SESSION['username']);
}
}
set_latst_action is simply just:
function set_last_active($mysqli, $username) {
if ($stmt = $mysqli->prepare("UPDATE Users SET lastActive = Now() WHERE username = ?")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->close();
}
}
then when I want to see if a user is online for example on a profile page I call isOnline();
function isOnline($mysqli, $username) {
if ($stmt = $mysqli->prepare("SELECT lastActive FROM Users WHERE username = ? LIMIT 1")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($return);
$stmt->fetch();
$lastActive = $return;
} else {
// user does not exist
$lastActive = "";
return $lastActive;
$stmt->close();
}
} else {
// SELECT failed
$lastActive = "";
return $lastActive;
$stmt->close();
}
if (!empty($lastActive)) {
date_default_timezone_set("Europe/London");
$dateNow = new DateTime;
$lastActiveDate = new DateTime($lastActive);
$diff=$dateNow->diff($lastActiveDate);
$hours = $diff->format('%h');
$mins = $diff->format('%i');
$day = $diff->format('%d');
$month = $diff->format('%m');
$year = $diff->format('%y');
if ($mins > 45 || $hours >= 1 || $days >= 1 || $month >= 1 || $year >= 1) {
$return = "Offline";
return $return;
}
else {
$return = "Online";
return $return;
}
}
else {
$return = "Offline";
return $return;
}
}