PHP: Destroy session variables [duplicate] - javascript

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>

Related

Redirecting to another page when login is valid, otherwise stay on the same page [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 years ago.
I'm fairly new with PHP programming and still getting myself familiar with the methods and syntax. Right now, I have no knowledge of session yet.
I want the user to get a message that the "user doesn't exist or incorrect login details" if he/she types incorrect login details on the form. Otherwise, redirect user to the next page.
I tried using the header() method of PHP but when I put it after the alert() message line, my alert() message doesn't even show.
nextpage.php
<?php
if(isset($_POST['btnLogin'])){
$con = mysqli_connect("localhost","root","","myDb")or die("cannot connect");
if(!$con){
die("Connection failed: " . mysqli_connect_errno() );
}
$studentNo = $_POST['studentNo'];
$username = $_POST['userName'];
$password = $_POST['password'];
$selectQuery = "SELECT * FROM registered WHERE student_no = '$studentNo' AND username = '$username' AND password = '$password' ";
$result = mysqli_query($con,$selectQuery);
if(mysqli_num_rows($result) == 0){
echo '<script language="javascript">';
echo 'alert("User doesn\'t exist or incorrect login details")';
echo '</script>';
header("Location: login.php"); //take user back to login.php if user doesn't exist
}else{
//do this if user exists
//get Parameters for studentNo, userName, password
}
}
?>
login.php
<form action="nextpage.php" method="POST">
<label>Student No</label>
<input type="text" name="studentNo" placeholder="Student No" required />
<br />
<label>Username</label>
<input type="text" name="userName" placeholder="Username" required />
<br />
<label>Password</label>
<input type="password" name="password" placeholder="Password" required />
<br />
<button type="submit" name="btnLogin">Login</button>
</form>
header() takes user back to login.php but it doesn't display the message.
Is there any other better way to do what I'm trying to do? Validate the login details first before redirecting to page two. Otherwise, don't redirect.
I researched and found that I can post data through <form> or other javascript syntax. I would prefer to learn how to do it with plain php and html
I hope you can help me.
Thank you.
You can display a message on the login page itself by adding a value onto the header itself and having an if statement on your login.php.
For example, change your header to
header("Location: login.php?error=1");
And on your login.php file, add this.
if(isset($_GET['error']) && $_GET['error'] == "1") {
echo '<div class="alert alert-danger">Login failed</div>
}
EDIT: Having seen CD001's comment, i'd recommend reading up on php & mysql on how to better protect yourself from sql injections etc. Here is a good place to start.
First of all, you cannot send a header() when you have already echo'ed output.
Secondly, the alert will never show up, even if redirecting would work, because the <script> is not on login.php. It is not magically stored somewhere to showup later.
Using session you can do like this
In your login.php before html code put this
<?php
session_start();
?>
This will start the session. When user submits the form, in nextpage.php, first you need to put again session_start(); on top of the script, after doing users authentication, you can set session like this
if(mysqli_num_rows($result) == 0){
header("Location: login.php?error=User doesnot exists"); //take user back to login.php if user doesn't exist
}else{
//do this if user exists
//get Parameters for studentNo, userName, password
$_SESSION['user_id'] = '<userId>';
//..
header("Location: <secure_page>");
}
In the secure_page where you've redirected the user, in that php script again on top of the script put session_start(); and after that you can check session
if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] != "") {
header("Location: login.php?error=access denied");
}
This will make sure that un-authenticated users can't access this page.
About the issue of not showing alert
In you're script, where you're using javascript code, there you'll need to add the type.
echo '<script type="text/javascript" language="javascript">';
Another problem with the code is javascript will execute only after you're page is loaded but after echoing all those you're using header("location:login.php"); which will redirect the user without showing javascript alert
Well like others said there are better ways of doing this but if you still want to go with your solution then this will work for you:
echo '<script language="javascript">';
echo 'alert("User doesnt exist or incorrect login details");';
echo 'location.href="http://www.yoursite.com/login.php";';
echo '</script>';
remove the php header redirection.

onclick event with PHP SESSION variable happening on every page load

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 :)

Destroy session using popup message

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.

PHP session not persistent with AJAX

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!";
}
?>

Automatically 'refreshing' the woocommerce's shopping cart when programmatically adding to a cart

I am using woocommerce in wordpress.
I am showing the shopping cart in one of my pages using the following :
<div id="shopping-cart"><?php echo do_shortcode('[woocommerce_cart]');?></div>
I am adding a product to this cart using my own function when a user clicks a button by using this code:
function addToCart(p_id){
alert("Adding to cart:"+p_id);
jQuery.get('/wordpress/?post_type=product&add-to-cart=' + p_id, function(response) {
// call back
alert(response);
});
//jQuery("#shopping-cart").append("[woocommerce_cart]");
alert("Added to cart:"+p_id);
}
I am calling this javascript by the following code :
<button type="button" onclick="return addToCart(18);">Add to cart</button>
The code works but the cart created using the do_shortcode does not update after the ajax request completes.
Can somebody please tell me how to make the cart update automatically when the get request completes?
Documentation to the rescue :)
// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php)
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');
function woocommerce_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
You'll probably need to tweak the HTML to suit your design.
In the end I create an Ajax call which called a PHP function which returned the result of calling do_shortcode('[woocommerce_cart]'); which I then simply put into the same div after emptying it - works nicely :)
I had to use Ajax through woocommerce to actually get the do_shortcode call in the PHP to run successfully as per :
http://codex.wordpress.org/AJAX_in_Plugins
Try adding this code after the Added to Cart alert...
location.reload();

Categories