I'm trying to implement a logout mechanism, which would consist of a link to click that should set a SESSION variable to True, send the user to the login page where PHP will check the value of the same variable and destroy the cookie before regenerating the session if it's set to true. The problem is that what should happen as an onclick event happens every time I load the page (And I can confirm this by echoing the variable at the top of the page, which returns always 1) except for the first time, where instead I get an error message because the variable is still not set. Here's my code:
JavaScript:
<script>
function destroy_session(){
<?php $_SESSION["Logout"]=True; ?>
}
document.getElementById("logout").onclick=destroy_session;
</script>
HTML:
<li><i class="fa fa-sign-out fa-fw"></i> Logout
PHP:
if ($_SESSION['Logout']){
session_unset();
session_destroy();
session_start();
}
Am I doing something wrong? Is there a way to fix this?
js:
function profile_logout(){
$('#response').html("Please wait...");
$.post( "/logout.php", function( data ) {
$('#response').html(data);
});
return false;
}
html:
<li id="response"><i class="fa fa-sign-out fa-fw"></i> Logout
logout.php:
<?php
#session_start();
session_unset();
session_destroy();
echo "Logout success !";
?>
Note: don't forget add library jquery
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
this is for example :)
Related
This question already has answers here:
Delete cookie php
(3 answers)
Closed 5 years ago.
I am trying to make a login php, but I need to stay logged in. I firstly used cookies but everybody said that I need to use session cookies. I succeded to save the session variables but now I am working on the logout button, that has an onclick event that toggles a function. It doesn't work.
Here is the code:
JQuery function -
function logout() {
$('body').append("<?php session_unset(); session_destroy(); ?>");
location.assign("index.php");
}
PHP -
<?php
if(!isset($_SESSION["username"]) || !isset($_SESSION["password"])){
echo '<button type="button" name="button" onclick="showRegister();">Register</button>
<button type="button" name="button" onclick="showLogin();">Login</button>';
}else{
echo '<button type="button" name="button">Publica un anunt</button>
<button type="button" name="button" onclick="logout();">Logout</button>';
}
?>
When you're doing
function logout() {
$('body').append("<?php session_unset(); session_destroy(); ?>");
location.assign("index.php");
}
On javascript - it only includes PHP code to the client-side page, doesn't executes it on server side.
If you need to logout - you need to build page logout.php like
<?php
session_unset(); session_destroy();
?>
And request it with ajax, like this:
function logout() {
$.ajax({
url: 'logout.php',
success: function(){
location.assign("index.php");
}
});
}
Or you can build logout.php like this:
<?php
session_unset(); session_destroy();
header("Location: index.php");
?>
And follow user to it by the link without any ajax, like this:
<a href='logout.php'>Log out</a>
I have set session, and whant to display popup only once when user enters site, But my popup is displaying all time, Below is my code -
<?php
Mage::getSingleton('core/session')->setWall('1');
$wall = Mage::getSingleton('core/session')->getWall();
if($wall =='1'){ ?>
<script>
jQuery(document).ready(function() {
jQuery('#earn-reward-box').show();
//jQuery('#earn-reward-box').delay(000).fadeOut();
});
</script>
<div id="earn-reward-box-main" style="display:block">
<div id="earn-reward-box" class="xmus-box">
<div id="earn-reward-close"> </div>
<a href="<?php echo Mage::getBaseUrl()?>christmas">
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);?>wysiwyg/deal.png" />
</a>
</div>
<div id="earn-reward-overlay"> </div>
</div><script>
jQuery('#earn-reward-close').click(function(){
jQuery('#earn-reward-box-main').toggle();
});
jQuery('#earn-reward-close').click(function(){
jQuery('#earn-reward-overlay').toggle();
});
</script>
<?php
Mage::getSingleton('core/session')->setWall('1');
}
Mage::getSingleton('core/session')->unsWall();
?>
Set session variable as "display:block" once it shows up and is closed change it to "display:none" and set it at style="here is the session variable".
you could make it show for every new session by saving to the sessionStorage like this
jQuery(document).ready(function() {
if(window.sessionStorage.getItem('shown') === true ){
jQuery('#earn-reward-box').show();
}
});
And you can set your item to true when the user clicks on the overlay
jQuery('#earn-reward-close').click(function(){
window.sessionStorage.setItem('shown', true);
jQuery('#earn-reward-box-main').toggle();
});
Seeing from MVC, you need a Model(or State) stored somewhere to tell if the popup has shown already or not. For example you can use localStorage as the place to store this information:
localStorage.setItem('popup-shown', 'true');
And the next time you open this page, since localStorage remains, you can tell if it has been shown already or not:
localStorage.getItem('popup-shown') === 'true'
Then you can control the behaviors of you popup as you need.
sessionStorage might be also fine, but take care of this quote:
sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends.
https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage
I want that when I click the logout button then it will destroy the session it runs perfectly but the issue is when I click on the cancel button of the popup it destroys the session even then.
below is the code.
index.php
<script>
function logout(){
if (confirm('Are you sure you want to logout?')){
return true;
<?php echo session_unset(); ?>
}else{
return false;
}
}
</script>
<b>click the Register link</b>
You can't destroy session without AJAX or relaoding. In your case , the following ligne
<?php echo session_unset(); ?>
Is executed when the page are displayed, Javascript doesn't execute php instruction.
So create a WebForm who will send a parameter in post or do ajax =)
<?php echo session_unset(); ?> have already destroyed the session whether confirm or not user to logout. because <?php echo session_unset(); ?> have already executed and destroied the session
Try this solution instead
create a new file logout.php with the code
<?php
session_start();
session_destroy(); // or session_unset('session_name'); to dystroy individual session
header("Location: http://www.yourwebsite.com/home.php"); // to redirect user after logout
?>
and on javascript side
<script>
function logout(){
if (confirm('Are you sure you want to logout?')){
window.location = "/logout.php";
return true;
}else{
return false;
}
}
</script>
You can simply unset session on registration page.
I'm working on making a website (developing locally) that requires a login for users; I've used php-login.net framework as my starting point and have my code talking to MySQL and creating sessions just fine.
I've gone through most every SO question regarding php sessions and ajax; but I still can't get my code to work how I want.
Now, I'm using ajax to call some other php scripts after the user successfully logs in, however it's not working properly. In firefox, with all the cookies, history, etc cleared, it looks like the session variables aren't maintained with the ajax call. However, if I log-out and then log back in, the session variables seem to be passed properly across ajax.
For example:
In my logged_in.php script, I'm using ajax to call another script: view_samples.php.
logged_in.php
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButtons.js
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
url: "view_samples.php",
cache: false,
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
When I log in with a browser that hasn't logged in before, I see it sets a session ID X; however when the button is pressed and the ajax call is made, I see a new session ID Y. I then log-out and log back in and see that my session ID is Y (before ajax) and that my session ID is Y when I click the button (after ajax).
I've also noticed that if I keep logging-in & out without pressing the view samples button, a new session id generated each time. However, as soon as I press the button, a whole new session id is created which seems to always be the one that is set if I log-out and then back in.
What am I missing? What's the proper way to go about ensuring the first session that is created is maintained throughout ajax calls? Should I POST the session id to the called script?
This is how I solved things (as Freaktor's comment above didn't resolve the issue) - I'm manually passing the session ID through AJAX and then setting it in the new PHP script. I'm wondering if anyone could comment on the security of this (as I'm not entirely sure how this all works)?
This and this post were helpful.
logged_in.php
<script>var session_id = '<?php echo session_id();?>';</script> <!-- store our session ID so that we can pass it through ajax -->
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButton.js
var data = {func:'getData1',session_id:session_id}; // manually send the session ID through ajax
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
type: "POST",
data: data,
url: "view_samples.php",
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_id($_POST['session_id']); // get the session ID sent by AJAX and set it
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});