Display a different sentences each time user visites a page - javascript

A thought would be to have different welcome message displayed each time user visites a page, like:
First visit -
Welcome
Second visit -
Hi again
Next visit and forever after -
no message
Can anyone tell me how would I would be able to accomplish this?

You can think of using cookies on the client side,
Cookies can be created with javascript or even with server side languages.
An example of storing user information on cookie using javascript would be like,
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
Use setcookie method to create a cookie with PHP. This cookie will expire after 30 days.
$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
So using cookies you can track the user visits, you could fetch a different welcome message from the db, each time a user visit your site.

For the first time user visits the page, put a value to session.
when he comes back check if the session value exists, then show "Hi again" message, and set another value in session.
check if the value exists show "no message".
if(session value for first visit exist) {
show "Hi again" message
}
else if(session value for second visit exist) {
}
else {
show welcome message
}

Related

How do I delete all cookies immediately after the browser is closed ( Using HTML and JavaScript )

What my site is and it's bare bones
A basic site made of HTML, CSS and Vanilla JavaScript. I am integrating front-end password protection to the site using JavaScript to check the credentials and assign a cookie which marks them as logged-in. It's just a side-project and security of the content isn't very necessary. The target audience also doesn't have the knowledge of adding cookies from the browser or manipulating the system in any way.
Once the user has signed in, they get redirected to the homepage, where the cookie is checked for. If the log-in cookie is present, they page loads, and if it's not present, the user gets redirected to the log-in page with a note asking to sign in. So far so good.
What's going wrong?
Like most web devs, I started testing the site before giving it a green signal, and turns out Chrome does not clear cookies after I close the browser. This is a spoilsport. Then, I tried using the onunload function on all the pages to delete the cookies, but the cookies are getting deleted even before the user reaches the homepage, and as a result, are directed to the homepage. I don't want to use Session Storage as opening the site in another tab does not take the Session Storage to the other tab.
Is there any way I could achieve deleting cookies when the browser is closed?
Since you're doing all this programming on the client-side, not the server-side, a cookie may not be the best approach - cookies are for transferring persistent information between the client and server. Local Storage may be a more appropriate choice, for controllable semi-persistent data stored on the client. Local Storage persists over different tabs on the same site.
A possible approach would be to have the saved data expire a certain amount of time after any page on your site has last been opened. For example, you could have, on every page, a script that runs every minute or five and sets the expiry time to an hour or 10 minutes in the future, or something like that - depends how much fine control you want over when logout occurs after inactivity. The code would look something like this:
// on pageload:
const advanceExpiry = () => {
localStorage.loginExpiry = Date.now() + 1000 * 60 * 10;
};
const loggedIn = localStorage.loginExpiry && localStorage.loginExpiry > Date.now();
if (loggedIn) {
advanceExpiry();
// every few minutes, push login expiry 10 minutes in the future:
setInterval(advanceExpiry, 1000 * 60 * 5);
} else {
// user has not logged in, or login has expired
localStorage.loginExpiry = 0;
// redirect to login page
}
and, on the login page, do localStorage.loginExpiry = Date.now() + 1000 * 60 * 10; followed by a redirect.
Just to point out, validation on the front-end is not remotely secure - but you already know about that and don't think it matters, which is fine.
There isn't a silver bullet readily available for your problem. However, using a Service Worker in conjunction with the Task Scheduling API and some JavaScript, you will reach close.
More info - Task Scheduling
Delete all cookies after an hour
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
setTimeout for 1hour
function myFunction() {
myVar = setTimeout(deleteAllCookies, 3600000);
}
Call myFunction when user login's or when he or she starts the application.

How to create multiple timer based on the timestamp of a data in database or delay the popup of the data base on the timestamp or time

Here I have shopping cart website and when a user check out it will go to the database name checkout. Then the admin will check the details of the user items then click accepted and it will go to db name pending payment. it will then notify the user that 4 hrs from now please pay using any credit card or else it will be deleted. I got a column name timer in my pending payment db which is a timestamp and another column name time which will get the date and time data . Im only doing this type of payment because I still don't know how to create a paypal payment so Im just checking my balance as a way of verification it will be temporary and also to have more choices wether it can be done using timestamp or date in php code like H/h/y/s something like that. Now if a user sends in a data then a timestamp appears in the database or (3/11/2019 5:03pm) for the time . Which will I fetch like this
$sql="SELECT * FROM pendingpayment;";
$sttmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($sttmt,$sql)){
echo "sql statement failed in displayitems.php line 71";
}else{
mysqli_stmt_execute($sttmt);
$ressult=mysqli_stmt_get_result($sttmt);
if(mysqli_num_rows($ressult)>0){
while($rowz=mysqli_fetch_assoc($ressult)){
for the timestamp
$rowz=['timestamp'];
for the time the user insert a data
$rowz['time'];
}}}
this is the output of the timestamp
2019-03-10 22:41:26
and the output of the time is up to you
now I want to create an alarm in that timestamp or time. that will notify the user 4 hrs from now. For ex. user sends in data at 5pm then admin accepted it at 6 it will notify the user like (4hrs from now please pay or else deleted which has a timer 6-10pm )is it possible using php or js?
or should I delay the popup of the data by 4 hrs from now? like I select * in db then popup only 4 hrs from now based on the timestamp or time
my way of notification is inserting data into the db name notification then I just select * and display it
the sleep function works in this like
if(isset($_POST['bla'])){
sleep(10);
$bla=$_POST['bla'];
$sql="INSERT INTO checkout(fname) VALUES(?);";
$stmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
echo "error in sql";
}else{
mysqli_stmt_bind_param($stmt,'s',$bla);
mysqli_stmt_execute($stmt);
}
}
even if the user delete the browser it will still insert the data into the db after 5 seconds

Countdown timer to logout of application [duplicate]

This question already has answers here:
How do I expire a PHP session after 30 minutes?
(17 answers)
Closed 5 years ago.
I have developed a staff record system for my company. The problem im facing is that the staff leaves their systems logged on and even forget to logout. I want the system to logout the user after leaving the system idle for 10 minutes. I have virtually no idea on how to go about it. I need your help
I've built functionality similar to what you're trying to achieve in the past using jQuery Idle. It detects mouse and keyboard activity and only times out when a user is truly inactive.
https://github.com/kidh0/jquery.idle
Example:
$(document).idle({
onIdle: function(){
windlow.location.href = '/logout.php';
},
idle: 10000
})
You can use this kind of code.
<!-- //for 10 minutes // the easiest one!-->
<meta http-equiv="refresh" content="600;url=logout.php" />
Keep in mind the logout.php need some code like this
session_start();
session_destroy();
unset($_SESSION);
header("Location: 'index.php?stayedToLong=yes');
exit;
Or SESSION in php something like
session_start();
//measure the time
$_SESSION['loggedTime'] = time();
//10 minutes
if($_SESSION['loggedTime'] < time()+10*60)
{
session_destroy();
unset( $_SESSION );
header("Location: 'index.php?stayedToLong=yes');
exit;
}
In the index.php page from the redirection index?stayedToLong=yes, you can show the page like this.
if(isset($_GET['stayedToLong']) && $_GET['stayedToLong']=='yes')
{
echo 'You have are disconnected after 10 minutes';
}
There's a couple of methods here. First off, your server should be clearing sessions after a certain time has elapsed. Your server should also have some way to refresh that session, typically an api endpoint of some sort that simply refreshes the session to keep it active.
In combination with that, in order to avoid an issue where your server session has ended but your front end session has not, you'll want to use a timer in javascript that requests the session value every few minutes. If that session ever returns inactive then you'll want to either display a modal or popup allowing the user to continue their session or you'll want to just automatically redirect them to a page that tells the user their session has expired.
In javascript your solution might look something like the following.
function confirmSessionRefresh(){
if( confirm('Your session will expire in 1 minute. Click Ok to continue or cancel to log out in 1 minute.') ){
fetch('/api/refreshsession');
setTimeout(confirmSessionRefresh, 540000);
}
}
setTimeout(confirmSessionRefresh, 540000); // 9 minutes (to allow 1 minute to respond to the prompt.

Sending Ajax Call When User Exits

I want to remove user stored data in my database when the user exits the page. A window dialog box will come up asking if the user really wishes to exit the page. Upon confirming to leave, an Ajax call should be sent to PHP confirming the action. Is it possible for PHP to receive the call in time and execute the command? If not, are there any other ways to verify that the Ajax call is sent successfully and the command is executed?
If you need very short-lived data (only relevant while the user is on the page), a database is not the right tool. Databases are designed to store long-lived data.
I suggest you use sessions instead. Here's a quick intro. Basically, sessions allow you to persist data across http requests, but to expire that data after a short while.
Start the session when the user logs in or opens your entry page, and store in $_SESSION any data you want to access while the user is on the page.
entry or login page
<?php
if(session_status()===PHP_SESSION_NONE) session_start();
... work through your script
//store data you'll need later
$_SESSION['username'] = 'Linda';
$_SESSION['age'] = 22;
$_SESSION['expires'] = time()+ 60*15; //expires in 15 minutes
The next time the user makes a request, test whether the session is still active. If so you can get the data from session, and refresh expiration. If the session has expired, you can destroy the data.
protected page
<?php
if(session_status()===PHP_SESSION_NONE) session_start();
if(isset($_SESSION['expires']) && $_SESSION['expires'] > time()){
//session is still active. extend expiration time
$_SESSION['expiration'] = time() + 60*15;
//retrieve data
$user = $_SESSION['username'];
.... run your script
}else{
//either the session doesn't exist or it has expired because the user
//left the page or stopped browsing the site
//destroy the session and redirect the user
session_destroy();
header('Location: /login.php');
}
You should not use unreliable, hacky and annoying methods. The only events that come close to your needs are window.onbeforeunload and window.unload but popups are usually blocked in those events (hence the hacky) and when blocked the remainder code as well.
There is also the issue that closing a tab will fire the events, closing the browser however will skip them and its all dependent if the browser actually supports it.
Perhaps use an ajax call every 5 minutes to detect if the page is still running and update a database with that time.
Now with a server cronjob you should select all rows with a time < now() - 300 and then you should have a list of browsers that recently connected but are not sending any signal anymore.
Or you could save the data in localstorage every 10 seconds so then there is no need to do all this?
Try This:
<script>
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
//ajax call here
}
if (event) {
event.returnValue = message;
}
return message;
};
</script>

Cookie not being deleted after session closed

I'm using cookies that should be deleted after user closes the page, but they're not. This is how I set cookies with JS
document.cookie="status=false";
I can see the cookie in console and after I close browser and open it again and go to my webpage there's still cookie status=false any idea why?
I solved it with this "trick", I don't know why I can't get cookies to work
window.onbeforeunload = function() {
document.cookie="status=false";
};
document.cookie = ... sets individual cookie values, it does not set "the entire cookie" to the string you passed, so setting "status=false" simply binds or updates the "status" value, irrespective of whatever else is in the cookie:
document.cookie = "cow=bell";
document.cookie = "cat=lol";
// cookie is now "cow=bell&cat=lol", not just "cat=lol"
If you want to delete the entire cookie, set its expiration time to "in the past" and the browser will do the cleanup for you.
(As pointed out in a comment, if you never set an expiration timestamp for your cookie, it'l expire when the page session ends, e.g. you close the tab/browser)
I was actually doing this today. A great reference is the Mozilla cookie documents if you create a js with their var docCookies code then using the functions provided like docCookies.setItem() docCookies.setItem() docCookies.getItem() or docCookies.removeItem() work incredible well.

Categories