In my application I need to make sure that if a user moves away from the application (by closing the tab, closing the browser, or navigation to another page) that if they try to come back to the application (using the back button, history, or typing the link) they are directed to a screen that makes them log back in.
I think I have this all worked out:
On every page, check to see if my session is available.
If it is, move on. If not, redirect to "You must log in again." page.
On the window.onbeforeunload() event, run a destroy.php script.
The destroy script kills the session.
But I can NOT get my destroy script loaded from the onbeforeunload() event.
Here is the index file, that starts things off:
<?php
/***********************
INDEX for CloseTab test
************************/
// Start the session
echo "<pre>";
echo "Starting session now...";
session_start();
// Put something in the variable that we can get on another page
$_SESSION["name"] = "Joe";
echo "\nJust set session var 'name' to 'Joe'.";
?>
<!-- Open that other page -->
<a href= <?php echo "home.php"; ?> > Click here to open Home page</a>
Here is the HOME page, just to have somewhere to go and test for the session:
<head>
<!-- ***********************
HOME for CloseTab test
************************** -->
<!-- Link to jQuery file -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<!-- Link to our custom js code.. -->
<script type="text/javascript" src=<?php echo "my_scripts.js></script>
</head>
<?php
// Start the session
session_start();
// See if there is any indication that a session is not available.
// Test with closing tab, closing browser, navigating away from page.
// We want to see this message if the user is coming here from anywhere except the index page.
// Test back button, typing the URL, browser history.
if ( (!isset($_SESSION)) || (session_status() == PHP_SESSION_NONE) || (count($_SESSION) < 1) ) {
echo "<pre>";
echo "Your session is not longer active. Log in again.";
echo "\n\nPretending to go to a login page...";
exit;
}
?>
<!-- If the session is good, we MUST have come from index page, and can access the session var. -->
<div class="container">
<h1>Home Page</h1>
<h2>Here is the name from the session var: <?php echo $_SESSION["name"]; ?> </h2>
</div>
<div>
<h3><a href= <?php echo "destroy.php"; ?> > Click here to log out</a></h3>
</div>
</html>
Here is my javascript code:
/***********************
my_scripts.js
************************/
console.log("in js file");
// Before a page unloads, run the destroy code
window.onbeforeunload = function() {
console.log("inside onbeforeunload"); // I get this to print
// Try to execute with AJAX call // Nothing in the middle seems to be running
$.ajax({
type: "GET",
url: "destroy.php",
async: false
});
// Try with jQuery syntax
$("container").load("destroy.php");
console.log("Got this far"); // I get this to print
}
Here is the destroy code I am trying to load:
<?php
/******************************************************************
Destroy
- Clears the session var and destroys the session if user leaves app.
******************************************************************/
// Unset all of the session variables and destroy the session.
session_start();
$_SESSION = array();
session_destroy();
?>
<script type="text/javascript">
// Place message in the console that we can see even if the window closes.
console.log("DONE! Session destroyed.")
</script>
You need to be careful with onbeforeunload. Browsers don't let you do too much in this event.
If you want to make an AJAX call, you need to add async: false. That's something that's usually discouraged, but here, if the call is asynchronous, then the browser will probably finish the event and close the page before the call is done.
$.ajax({
type: "GET",
url: "destroy.php",
async: false
});
Related
Something like the below does not work:
<?php $nojs = false; ?>
<noscript>
<?php $nojs = true; ?>
</noscript>
As the PHP is executed regardless if JS is enabled or not. But is there a way to get a similar effect? I'm trying to set a flag if JS is disabled and then display parts of the page accordingly.
PHP is executed before javascript, so you cannot do this. You can do something such as executing a basic ajax request and storing hasjs in a session variable once the ajax page is successfully queried. You wouldn't know if it's just the fact that the ajax request wasn't successful due to something else, or if they have Javascript disabled.
Lets give this a shot anyway:
The jquery script in your head tags
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$.get( "hasjs.php", { hasjs: "1"} );
});
</script>
The PHP file (hasjs.php)
<?php
if(isset($_GET['hasjs']))
{
session_start();
$_SESSION['hasjs'] = 1;
}
?>
Then you can access the session variable to determine if they have JS based off the ajax query. Nothing stopping the user from visiting that page though if they don't have JS installed.
We felt in a procedure in php to show a process bar while performing a task, but in the Chrome browser does not display the bar until the process ends. In other browsers like Chromium it works perfectly and shows the progress bar. Any suggestions?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
// Total processes
$total = 10;
// Loop through process
for($i=1; $i<=$total; $i++){
// Calculate the percentation
$percent = intval($i/$total * 100)."%";
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\"> </div>";
document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
// Send output to browser immediately
flush();
// Sleep one second so we can see the delay
sleep(1);
}
// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>
</body>
I'm gonna be one of those annoying people that ask why are you doing something.
Do you actually need to stream the data from the server to the browser ?
Unless you are sending huge amounts of generated data to the user, there is really no need for such measures.
Because you are not using WebSockets, you could save the information about the process into the cookie, so that you do not have to store it anywhere else, and it is related to an individual client, and send an AJAX request to a dedicated page that will return the percentage, or the state of this process.
While the process is going on you just need to call setcookie with the correct values, something like
setcookie($name, $value, $expiration /*<--- does not matter*/);
and in the dedicated page that returns this value
return $_COOKIE[$name]; //<--- $name the same as in setcookie,
//this should probably return JSON
and in the js code you would ( with jquery, cause its easier )
$.get(page, function(data)
{
document.getElementById("progress").innerHTML =
'<div style="width: data;background-color:#ddd;"></div>';
}
Hope this helps.
I'm using sessionStorage successfully in a project, with one caveat: I can't eliminate the storage with the clear() operator, as documented.
I'm doing this when logging out of the administrative mode of my site, which involves clicking on a Log Out item in a list, like this:
<li>Log Out</li>
The admin_logout.php file then destroys session variables, etc., and then redirects to the home page of the site. Its previous form, which works, is:
<?php
session_start();
session_destroy();
#header('Location:./');
exit;
?>
That all works fine. What I can't seem to integrate into the routine is clearing the sessionStorage. For the text of my admin_logout.php file, I've tried:
<?php
session_start();
?>
<script>
sessionStorage.clear();
</script>
<?php
session_destroy();
#header('Location:./');
exit;
?>
...as well as:
<?php
session_start();
echo '<script>';
echo 'sessionStorage.clear();';
echo '</script>';
session_destroy();
#header('Location:./');
exit;
?>
Perhaps pointing to the root cause is that when I've placed:
?>
<script>
alert("HELLO");
</script>
<?php
...within this script, the alert is never executed, yet everything else is. How can I invoke the <script> based sessionStorage.clear() operation to clear my session storage items within the routine listed above?
I think it's because you're redirecting on the server-side and the sessionStorage.clear() is happening on the client side. I believe you're redirecting before that gets a chance to run.
Allicam was correct; I needed to encapsulate the storage clearing code in a callback function:
<?php
session_start();
session_destroy();
<script type="text/javascript">
function firstFunction(_callback){
sessionStorage.clear();
_callback();
}
function secondFunction(){
firstFunction(function() {
window.location = './';
});
}
secondFunction();
</script>
So i have a contact page that runs some php and in that php if the email sends through correctly it runs a javascript command. I have two javascript commands one to change page and one to alert the person sending the email. Here is the code:
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
window.location.assign("http://dtc.bz/twitch/index.html");
$('.alertfeed').show();
</script>
<?php
}else { ?>
<script language="javascript" type="text/javascript">
</script>
<?php
}
?>
When I run it. It redirects me to the correct page but the second command within the php page. So how do I get the second line of the javascript run on the page I want it to redirect to?
After the page redirection no code will be executed, that's the reason "$('.alertfeed').show();" is not getting triggered. To do this you have to redirect the page first and on the page you have redirected then execute the next command.
Something like
window.location.assign("http://dtc.bz/twitch/index.html?redirected=yes");
now on the index.html check if redirected param and execute this command in php
<?php if($_GET['redirected']=='yes')
{
echo "<script>$('.alertfeed').show();</script>";
}?>
Update: Using Jquery
$(document).ready(function(){
var url = window.location.pathname;
var pieces = url.split("?");
if(pieces[1]=='redirected=yes'){
$('.alertfeed').show();
}
});
Working Demo:
http://jsfiddle.net/sLEgJ/4/
Your are getting redirected because there is no condition given for redirecting.
Thats why its redirecting you every time you run it.
a page directs users back to a page automatically
<meta http-equiv="refresh" content="1; URL=http://localhost/mywebsite/Untitled9.php">
when it reaches 'Untitled9.php' i want it to display an alert box saying 'Message sucessfully posted'
I only want it to display when it id directed back to the page and not when first load
e.g Home - Message page = No alert
Home - message page - submit - redirect to message page = alert 'post sucessfully posted'
Can't control the DOM of a page externally.
What you could do however is pass a variable in the query string to the page you're redirecting to like this
Untitled9.php?message=success
Then on your new page have
<?php
session_start();
if ($_GET['message'] == "success" && $_SESSION['revisit'] == "0")
{
$_SESSION['revisit'] = "1";
?>
<script type="text/javascript">window.alert('Message successfully posted.');</script>
<?php
}
?>
In your first page change your code to look like this
<?php
session_start();
$_SESSION['revisit'] = "0";
?>
<meta http-equiv="refresh" content="1; URL=http://localhost/mywebsite/Untitled9.php">
If I understand your question correctly, this should work for you (assuming you alter the keys for the $_POST variables accordingly, of course):
<?php (isset($_POST['my_sub_btn'])): ?>
<script type="text/javascript">window.alert('Message successfully posted.');</script>
<?php endif ?>
Assuming you're submitting the message from a form, there should be no reason to redirect using a HTML redirect. Set the action attribute of your form to Untitled9.php and it will handle the rest...
Given your requirements, why not set a parameter on succes? Such as:
<meta http-equiv="refresh" content="1; URL=http://localhost/mywebsite/Untitled9.php?success=1">