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>
Related
I have a hyperlink and clicking on that link will run a JavaScript function. I also have a PHP variable $counter. Inside the JavaScript function, the value of $counter is increased by 1 i.e., $counter++. It works fine. But the same function also runs whenever the page is refreshed. So the value of the $counter is increased by 1 whenever the page is refreshed. I tried all the solutions available on the net like preventDefault(), clickevent handler etc., But nothing works. Please help to fix this. In the below code, I have set $counter as 0. But it loads with 1 as output. I want it to count only when the hyperlink is clicked. Here is my sample code.
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
function onclick() {
<?php
$counter++;
?>
}
</script>
</head>
<body>
link text
</body>
<?php
//tracing counter value
echo $counter;
?>
</html>
TL;DR:
You can't mix PHP and JS code expecting that JS function will execute PHP code.
First PHP prepares output to browser, then Browser parses your JS and HTML. JS never knows about PHP code.
Click CTRL+U to view source as browser sees it - there is no PHP code.
JS function is not run on page refresh. PHP code is run on page refresh.
First goes PHP parser:
session_start();
require("dbconfig.php");
$counter=0;
$counter++;
echo $counter;
Then goes JS/Html parser.
At this point your JS code looks like this:
function onclick() {
}
Content of function is empty because you output nothing from PHP side.
To fix it move PHP var to JS var:
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
var jsCounter = <?= $counter; ?>
function onclick() {
jsCounter++;
console.log(jsCounter);
}
</script>
</head>
<body>
link text
</body>
</html>
Note never output after closing body tag.
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
});
I am trying to include some JavaScript to just one single page of a WordPress based website. Basically, what I've done is in the header.php of the theme, I've put the following:
<?php if( is_page('17')) { ?>
<!--Start of Zopim Live Chat Script-->
<script type="text/javascript">
window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
_.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
$.src="//v2.zopim.com/?2pL2gooCVnWNWjh0QB7IVqRgAiarsW4o";z.t=+new Date;$.
type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
</script>
<!--End of Zopim Live Chat Script-->
<?php }
<?php endif; ?>
When I add this, it breaks the entire site, nothing loads anywhere. I've tried it with and without the
<?php endif; ?>
at the end, thinking that it may be duplicating with the
<?php }
I actually have two different conditional statements I need to add, each for a different page. I don't want to use the plugin that allows PHP & JavaScript in the pages themselves for security reasons, which is what I used to use.
Can anyone tell me what I'm doing wrong, and/or how to add this particular JavaScript to only page #17 (which I'm guessing will also show me how to add a PHP statement and link to single-use stylesheet that I need on a different page)?
It's hard to give a definite answer without seeing the rest of the page code but in my opinion you don't need the <?php endif; ?>.
Simply replace
<?php }
<?php endif; ?>
with
<?php } ?>
and it should work.
header('Location: ../homepage.html');
echo "<script language='javascript'> console.log('Email already exists'); </script>";
echo "<script> console.log('ccccc'); </script>";
I am just trying to create a registration form. When user tries to register with same Email Id, I want to go back to my html page and open login window[Trigger login click].
For initial try, i just try to console some strings after redirecting the page. I don't get those strings.
If i comment out header line, I get those two strings.
How do i solve this issue? Is there any alternative for my scenario?
I have separate html and php files.
EDIT:
if (mysqli_num_rows($result1) > 0)
{
//echo "This Email is already used.";
//Write code to go back to register window
/*echo '<script type="text/javascript">
console.log("cdsafcds");
$(".login_links_login").trigger("click");
</script>';*/
$_SESSION['email_exist']="Email Already Exists";
header('Location: ../homepage.php');
}
homepage.php Part:
<?php
if(isset($_SESSION['email_exist']))
{
echo "<script language'javascript'>conosle.log('Me');</script>";
}
?>
<html>
<head>
.......
<form class="right registerForm" id="registerForm" method="POST" action="lib/registration_validate.php">
......
when you use header('Location: ../homepage.php'); it wont execute the two lines afterward. That is the whole problem. You can do it either by passing variables through header like this : header('Location: ../homepage.php?log'); or setting session in your php script and use redirect afterwards.
You also need php file in order to catch the parameter you just send and use if like this :
if(isset($_GET['log'])){
echo "<script language='javascript'> console.log('Email already exists'); </script>";
echo "<script> console.log('ccccc'); </script>";
}
or :
if(isset($_SESSION['log'])){
echo "<script language='javascript'> console.log('Email already exists'); </script>";
echo "<script> console.log('ccccc'); </script>";
}
It depends on what method you used earlier. So turn your homepage.html into homepage.php and put it there.
I have a page named Index And a page chat
for check session write the code for print echo session->user;
this code work in chat.php but include chat.php in index.php echo session->user; not work
e:g
//index.php
<?php
<iframe src="./chat.php"></iframe>
enter code here
?>
//chat.php
<?php
include_once ('./session.php');
echo $session->user;
?>
chat.php printed user but index.php not print
Where is the problem?
Please help
While this problem is in Firefox not in IE problem
For me, this works for iframe, start the session like this:
header('P3P: CP="CAO PSA OUR"');
session_start();
in chat.php and index.php remember to include
session_start()
unless it is automatically started in your php.ini
session_start()