i am trying to send an auto generated mail for wedding event so i have an countdown timer using java script and i want to send a reminder before a day . i tried in php and java script but i am not getting expected output.
Tried below code using java script, but it is not sending /displaying my message on the console
<!DOCTYPE html>
<html>
<p id="demo"></p>
<style>
p {
text-align: center;
color: #7FFF00;
font-size: 50px;
margin-top: 0px;
}
</style>
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 3, 2019 10:30:01").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Today is the wedding";
}
var myvar=20;
while(distance==myvar){
document.getElementById("demo").innerHTML = "Reminder";
<?php
//to send an wedding reminder
include "Sendmail.php"
?>
}
}, 1000);
</script>
</html>
Hence i tried with below Php using page auto refresh option:but it is not working as exected-------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("l");
//date_default_timezone_set('America/New_York');
//timezone_name_from_abbr('IHST',19800) for Asia/Colombo
//set the timezone for ist:
date_default_timezone_set('Asia/Kolkata');
$today = date("Y-m-d H:i:s");
$date = "2019-02-26 07:43:16 ";
$tilldate = "2019-02-26 07:43:50 ";
echo $today;
do {
$page = $_SERVER['PHP_SELF'];
$sec = "6";
//echo "Watch the page reload itself in 3 second!";
}while ( $date<=$today)
echo" when satisfied call my function and come out of loop";
break;
//if($today < $date ||$today < $tilldate){
//echo "Watch the page reload itself in 3 second!";
//break;
// echo "Watch the page reload itself in 3 second!";
//include 'FetchData.php';
//}
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
<?php
echo "Watch the page reload itself in six second!";
?>
</html>
It will be very helpful if some one assist me on this.
If your goal is to build a site where people can enter a wedding date, and have it email them a reminder a set time before, you will need to store that data on a server somehow.
If you are familiar with NodeJS you could use it to set up a small app that keeps the wedding dates in memory, (though longer-term storage is safer), and then you can use something like Nodemailer to send the email once the time is reached.
However if you don't know NodeJS, using Javascript alone won't be enough - and you can't call PHP code with JS using an embed like you're doing. Keep in mind that PHP is rendered out before any Javascript is run, so JS can't directly call a PHP function. In order to get JS to communicate with PHP in most cases you'll want to make an AJAX call to a PHP script on your server.
So your front end will be a page that uses JS to send an AJAX request containing a wedding date to a separate PHP script on your server. That PHP script will then save that data to the server, using something like mySQL, (or in a pinch you can just use fwrite( ) to write to the local file structure, though a full database system is safer.)
Now you'll need a 2nd PHP script that checks the data every minute or so, and sends an email when a wedding date is close enough. However, you don't want to use auto-refresh to keep a PHP script running. Instead you'll want to set up a cron task that calls your PHP script however often you need it to.
So the elements you'll need are: 1) HTML page containing Javascript, which sends AJAX data to 2) A PHP script that saves that data to your server, and 3) A 2nd PHP script, called by cron, which checks the data and emails when necessary
On the other hand, if all you need is an email reminder for one specific wedding, you'd probably be better off scheduling it through your email client, or using something like IFTTT.
Related
I have a php code as shown below in which session timeout happen after 60 mins when there is no activity. The following code is inside the file /mno.php. My login and logout code is also in the same file /mno.php.
/mno.php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
header('location: /mmo.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
The table trace_users in the code keeps the track of all logged in users. In that table, there are two columns user_name and open. The value is set to true/false when any user log in/log out.
I have included sql query in which I am trying to update a table when there is no activity but unfortunately the column value is not getting set to false for that particular user when no activity happens for 60 mins.
This is what I have tried:
After doing some research, I think I have to run a timer (js/ajax). In the javascript shown below I have calculated the difference between the Last Activity and the Current time.
If its more than 60 mins, then it will update a db table. This is what I have tried but I believe more need to be done in order to update a table in db.
<script>
let x = setInterval(function() {
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>
let now = <?php echo time() ?>;
let difference = now - lastActivity;
if (difference > 3600) {
clearInterval(x);
}
}, 1000
);
</script>
Problem Statement:
I am wondering what changes I should make in the js (or php) code above so that when there is no activity for 60 mins, it should update the column open to false (in the table trace_users) for that particular user.
Edit 1:
My login code and session history code is in the same file /mno.php. I have placed everything in the same file /mno.php.
I think Vineys and jo0gbe4bstjbs answer is wrong because of when user close browser until 5 seconds, it can't update table after 60 mins and session too. Session deletes just after time in where set in php.ini configuration file.
And Do you mind requesting every 5 seconds is it good way to solve this? It is worst for performance.
If you want solve this problem with professionalism, you should add "last_request" column and delete "open" column from the table and after every request you should update last_requests value to current unix timestamp. And where getting users you should write:
$time = time() - 3600;
"SELECT * FROM `users` WHERE last_request > $time" //active users
"SELECT * FROM `users` WHERE last_request <= $time" //inactive users
And instead of ajax request every 5 seconds you should write setTimeout with 3600 second delay time which run window.location.href= '/mmo.php'; code.
Its way good if you want best performance and exactly result with 60 minute logout
I suppose you realize that this code
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
//...
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
runs on every request and only when a request arrives
Imagine I visit your website and then go out shopping keeping the browser open. What do you think will happen?
NOTHING - because there will be no new request sent to you (assuming you haven't implemented any periodic ajax polling / Websocket mechanism)
So the server won't bother about me until I come back from shopping and refresh the page, only then would the server realize "Hmmm..This guy's LAST_ACTIVITY is older than an hour let me update my trace_users table and set open as false for him"
Coming to your proposed solution, it looks good and avoids the complications of websockets/periodic ajax requests
Just need some minor corrections, follow here for a basic demo
<script>
var lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
var now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server
// but later on it will be incremented by javascript to act as counter
var logoutAfter = 5; //I set 5 sec for demo purposes
var timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
}
}, 1000);
</script>
Here the lastActivity will hold the timestamp when the page was sent by server to browser it will be never changed by scripts on the browser,
now is your counter that you will use to track how much time passed since page was loaded on the browser, you'll increment it every second and check if a given amount of time has been crossed
If true do a ajax request (or simply redirect to logout.php) where you would destroy session and update the trace_users table to mark the user as closed
UPDATE
So ajax will be like
$.ajax({
url: "/close.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
window.location.href= '/mmo.php';
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
and
close.php
<?php
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
// I'm not sure whether the below if condition check is required here or not
// because we have already checked (whether to timeout or not ) in our javascript
// and we call close.php only when it's affirmative
// I encourage you to test and find out :)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Page.php
<!-- CODE TO INCLUDE IN HEADER.PHP -->
<?php
session_start();
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
<!-- CLOSE -->
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
let now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server+
// but later on it will be incremented by javascript to act as counter
let logoutAfter = 5; //I set 5 secs for demo purposes
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/mmo.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("I am inside error");
alert(textStatus);
}
});
}
}, 1000); //<-- you can increse it( till <= logoutAfter ) for better performance as suggested by #"Space Coding"
</script>
</html>
mmo.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name'])?$_SESSION['user_name']:'';
$stmt->bind_param('ss', $open, $usname );
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
This is a simple time validation for web page:
$modified_on = isset($SERVER['HTTP_IF_MODIFIED_SINCE']) ? $SERVER['HTTP_IF_MODIFIED_SINCE'] : null;
$current_time = time();
if (!is_null($modified_on) && ($current_time - strtotime($modified_on)) > 3600) {
session_destroy();
...
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $current_time).' GMT');
...
currently I am working on a online quiz platform and I want to show a quiz timer.first I use javascript to show timer but problem is that when user refresh a page or goes back the quiz timer start again form start so I want to use session variable time to show quiz timer. and I set this session variable when user start the quiz. but my code is not working properly. here is my code:
`<?php
include_once 'dbConnection.php';
session_start();
if(!(isset($_SESSION['email']))){
header("location:login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
// timer will start when document is loaded
$(document).ready( function () {
startTest();
});
var si;
function timer(){
<?php $_SESSION['time']-= 1000; ?>
var count="<?php echo $_SESSION['time']; ?>";
var min = Math.floor(count / (60 * 1000));
var sec = Math.floor((count - (min * 60 * 1000)) / 1000);
min = (min < 10)?'0'+min:min;
sec = (sec < 10)?'0'+sec:sec;
if (count <= 0){
document.getElementById('duration').innerHTML ="Time Up";
clearInterval(si);
// submit my quiz.
}
else {
document.getElementById('duration').innerHTML = "00:" + min + ":" + sec;
}
}
function startTest(){
si = setInterval( "timer()", 1000);
}
</script>
</head>
<body>
<p id="duration" >show time</p>
</body>
</html>`
this code is giving some unexpected error or doesn't work properly.
Remove the double quotes if its an integer
var count=<?php echo $_SESSION['time']; ?>;
What i understand from your description is that you need time duration from server side. so that if any one refresh the browser don't restart the timer from the beginning .
You need to calculate the time duration on server side. That can be achieved by using ajax call.
<?php
session_start();
$_SESSION['start_time'] = time();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// timer will start when document is loaded
$(document).ready( function () {
setInterval(() => {
$.ajax({
url:"timer.php", //path to your file
success:function(data) {
// do your code here
$('#duration').text(data);
}
});
}, 1000);
});
</script>
</head>
<body>
<p id="duration" >show time</p>
</body>
</html>
Create new php file for calculating time timer.php
<?php
session_start();
$start_time = $_SESSION['start_time']; // start time;
$from_time = time(); // current time;
$minutes = round(abs($start_time - $from_time) / 60);
$seconds = abs($to_time - $from_time) % 60;
echo "$minutes minutes & $seconds seconds";
?>
I have a code that is meant to refresh the page on the hour, every hour but it doesn't seem to execute...
This is the code:
<?php
date_default_timezone_set('Australia/Sydney');
$date = date("i:s");
list($cur_min, $cur_sec) = explode(':', $date);
$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;
$time=($mins_left*60+$secs_left)*1000;
?>
<script type="text/javascript">
setInterval("refresh()",<?php echo $time; ?>);
function refresh(){
window.location = location.href;
}
</script>
I need it to run off the server clock too and not from when the user lands on the page.
Idealy, would be awesome if it could just refresh the content of every div labeled with the class named "locality"...
I would use DateTime in PHP and for easy convertion use timestamps.
$date = new \DateTime(strtotime(time()), new \DateTimeZone("Australia/Sydney")));
$date->add(new \DateInterval('PT1H'));
$time = $date->format('U') % 3600;
And for JS:
var time = (Math.round((new Date()).getTime() / 1000) % 3600);
if(time > <?= $time ?>){
var rtime = time - <?= $time ?>;
} else {
var rtime = <?= $time ?> - time;
}
setInterval(function(){
window.location.reload(1);
},rtime * 1000);
But im not sure why:
<meta http-equiv="refresh" content="3600">
Will not suffice as it will just refresh an hour later (and so on) of when the user enters the page, doesn't really matter what timezone.
Try this code for the JavaScript part:
function refresh(){
window.location.reload();
}
setTimeout(refresh, <?php echo $time; ?>);
I'm not sure if it will solve your problem, but I tried a few changes:
window.location.reload() is more explicit than window.location = location.href (which, by the way, could be simplified to window.location = window.location)
setTimeout instead of setInterval because if the refreshing fails again for some reason, you don't want to try refreshing again in
put the setTimeout call after the definition of the function to be sure that there isn't a problem with the function not being defined yet
Try it. If that code still doesn't work for you, try looking at your generated HTML and seeing what value for $time was printed. Also check the browser console for any errors.
By the way, the code would be clearer if you renamed the variable $time to $ms_until_start_of_hour.
i've built a basic countdown timer in PHP which will echo the result back to be displayed on page by javascript every second (or every minute, I havent decided if doing a get call every second will cause any issues yet)
So the countdown works by taking input from a user and updating a DB serverside. PHP then takes this value, converts it into a time format and uses it to calculate the end time for the countdown.
My question is, I would like the timer to flash or something similar when the time changes based on new DB input... So for example the timer would be counting down to 2 hours. Another user submits the form which updates the database so now the end time is 5 hours away. Id like to somehow capture this change so I can display a message on the page.
I'm wracking my brains about how to do this but cannot think of a method.
basic PHP im using to calculate the end time
<?php
$timeUntil = 100; // placeholder, actual variable will be integer pulled from db
$unixTime = 86400;
$zTime = $timeUntil * $unixTime;
$endDate = time() + zTime;
$remaining = $endDate - time();
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
$minutes_remaining = floor((($remaining % 86400) % 3600) / 60);
$seconds_remaining = floor((($remaining % 86400) % 3600) % 60);
$zTimeCombined = array($days_remaining, $hours_remaining,
$minutes_remaining, $seconds_remaining);
echo $zTimeCombined;
?>
I would personally use websockets for this. Doing too many AJAX requests is the best way to kill your server. What you need for this is Ratchet on the PHP-side and WebSockets (no lib needed) on the JS-side.
On the server, onOpen, you would send the current timer time and you would send a new message to every client if the time is updated.
Here is a small example:
composer.json:
{
"require": {
"cboden/ratchet": "^0.3.3"
},
"autoload": {
"psr-4": {
"App\\": "App/"
}
}
}
socket.php:
<?php
require 'vendor/autoload.php';
use App\Chat;
use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
$var = new Chat;
$var = new WsServer($var);
$var = new HttpServer($var);
$var = IoServer::factory($var, 8080);
$var->run();
App/Chat.php:
<?php
namespace App;
use Ratchet\MessageComponentInterface;
use SplObjectStorage;
use Ratchet\ConnectionInterface as Connection;
use Exception;
class Chat implements MessageComponentInterface
{
public $clients;
public function __construct()
{
$this->clients = new SplObjectStorage;
}
public function onOpen(Connection $conn)
{
$this->clients->attach($conn);
}
public function onMessage(Connection $from, $msg)
{
foreach ($this->clients as $key => $value) {
if ($value != $from) {
$value->send($msg);
}
}
}
public function onClose(Connection $conn)
{
$this->clients->detach($conn);
}
public function onError(Connection $conn, Exception $e)
{
echo 'error: ' . $e->getMessage() . "\n";
$conn->close();
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Chat</title>
</head>
<body>
<div id="chat"></div>
<input type="text" id="input">
<input type="submit" id="submit">
<script type="text/javascript">
var socket = new WebSocket('ws://localhost:8080')
socket.onmessage = function (msg) {
addToChat(msg.data)
}
var input = document.getElementById('input')
var submit = document.getElementById('submit')
submit.addEventListener('click', function (e) {
e.preventDefault()
if (input.value.length > 0) {
addToChat(input.value)
socket.send(input.value)
input.value = ''
}
})
function addToChat(msg) {
document.getElementById('chat').innerHTML += '<p>' + msg + '</p>'
}
</script>
</body>
</html>
This is the socket Hello World: a chat. It is in it's simplest form, just a message sent, no username, time, etc. It basically is the Ratchet example but adapted to WebSockets.
To go further, do not hesitate to rely on documentation (Ratchet and MDN for JS-side).
On my php website I have many various countdowns. These are only updated when the user refreshes the page. I want to change it so that the countdown is continous.
I have found many javascript codes that perform this, however I'm unsure how to implement my php code into there script.
Please see below scripts:
My php function for timer:
function countup ($online){
global $time;
$difference=$online-$time;
$num = $difference/86400;
$days = intval($num);
$num2 = ($num - $days)*24;
$hours = intval($num2);
$num3 = ($num2 - $hours)*60;
$mins = intval($num3);
$num4 = ($num3 - $mins)*60;
$secs = intval($num4);
if($days != 0){echo"$days days, ";}
if($hours != 0){echo"$hours hours, ";}
if($mins != 0){echo"$mins minutes and ";}
echo"$secs seconds";
}
where I show the timer I have the following.. <?=countup($set[ends])?>
Ends = future unix timestamp.
The javascript countdown I came across was from http://keith-wood.name/countdown.html but I have no understanding of java and am not sure how to put $set[ends] into it!
All help would be greatly appreciated!
Considering, that you're loading all required scripts properly, here is what I would suggest:
PHP part
$ends = date("Y, n-1, j", $set[ends]); //covert your time stamp to the required format
**JavaScript Part **
<script type='text/javascript'>
( function( $ ) {
$('#yourCountDownDIV').countdown({until: <?php echo $ends ?>});
} )( jQuery );
</script>
Put the JavaScript part at the end of the HTML code just before the closing tag and after all your JavaScript files are loaded.