Destroy session using popup message - javascript

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.

Related

PHP header redirect not working if the session isnt set

I'm trying to check if the user hasnt logged in on a cart.php, if they arent -redirect them to login.php.
This isn't working so I tried putting it in an elseif statement. If they are logged in and are on the cart page, redirect them to the cart page, and if they arent redirect them to the login page.
It is working in the sense that it redirects, yet if I login, it still redirects to login.php.
Also I'm not sure why none of the JS alerts are working.
if (isset($_SESSION['username'])){
header("Location: http://localhost/techiteasy/cart.php");
}
else if (!isset($_SESSION['username'])){
header("Location: http://localhost/techiteasy/login.php");
echo '<script language="javascript">';
echo 'alert("Please Login/Register")';
echo '</script>';
}
After a redirect you can't add more code, the new page will call and the script of the new one will run.
You need somthing transfer from a page to another.
Usually i use a cookie with a short time (2-5 seconds), the new page will call check if the cookie is set, if it is show the alert and unset the cookie.
Here in the code you can see i put only an if statement (without else or else if) cause when the script fire the header location the next one code won't run and the new page will load.
if (!isset($_SESSION['username'])){
setcookie('notlogged', true, time() + 3;)
header("Location: http://localhost/techiteasy/login.php");
}
header("Location: http://localhost/techiteasy/cart.php");
In the login.php
if (isset($_COOKIE['notlogged']) && $_COOKIE['notlogged'] == true){
echo '<script language="javascript">';
echo 'alert("Please Login/Register")';
echo '</script>';
unset($_COOKIE['notlogged']);
}
Try this ;)
You can also not set an expired time, it is just to avoid errors, but remind to unset every time, in other case the user only logs without passing from cart will wiew the alert.
You can simply use as like below. Do not need to check negative condition again. Simply use if-else.
if (isset($_SESSION['username'])){
header("Location: http://localhost/techiteasy/cart.php");
}
else{
header("Location: http://localhost/techiteasy/login.php");
echo '<script language="javascript">';
echo 'alert("Please Login/Register")';
echo '</script>';
}
Try this on PHP5
if(isset($_SESSION['username'])){ header("Location: http://localhost/techiteasy/cart.php");
}
else{
if(!isset($_SESSION['username'])){
echo '<script>alert("Login with vaild user and pass");</script>';
header("Location: http://localhost/techiteasy/login.php");
exit;
}}
For PHP7
if(isset($_SESSION['username'])){ header("Location: http://localhost/techiteasy/cart.php, true, 301");
}
else{
if(!isset($_SESSION['username'])){
echo '<script>alert("Login with vaild user and pass");</script>';
header("Location: http://localhost/techiteasy/login.php, true, 301");
exit;
}}

PHP: Destroy session variables [duplicate]

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>

Redirect and popup when sql is done

I want to get my application when a item is deleted pop up a messege and redirect to another page. I used javascipt for the popup and php header for the redirection. Now its only doing or the popup or the redirect depending which one is listed first. how do i fix this?
<?php
session_start();
require_once('../../includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: ../../login.php');
$Cursist = mysqli_query($con, "SELECT id FROM users WHERE id =".$_SESSION['id']);
if(!$Cursist){
header('location: ../login.php');
}
$test = $_GET['id'];
$sql = "DELETE FROM cursus WHERE id = $test";
$result = mysqli_query($con, $sql);
if ($result) {
echo "<script type='text/javascript'>alert('Verwijdert!')</script>";
header("Location: ../cursussen.php?destoyed=true&destroyed_id=".$_GET['id']);
}else {
echo "mislukt";
}
?>
If you send sometrhing before header will not work. You can use only header before sending sometrhing to the client.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
You could do with javascript but It not recommended because the user could have javascript disabled:
echo "<script type='text/javascript'>";
echo "alert('Verwijdert!')";
echo "document.location.href='index.html'";
echo "</script>";
The best way is to use session and header, you can save a var in session and show a message when the var is true and when you show the messasge delete the session var
delete.php
$_SESSION['deleted'] = true;
header("Location: index.php);
index.php
<?php if($_SESSION['deleted']){ ?>
<?php unset($_SESSION['deleted']) ?>
<div>Item was deleted</div>
<?php } ?>
Well, the problem is that the redirect immediately moves you to a new page, so any javascript on the old page becomes irrelevant. You might be able to use a delay before redirect so that the javascript alert can display.
Otherwise, introduce a variable that you send to the redirect destination page, and use this variable to trigger a javascript popup there.

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

How do i reload the page after the sql statement has been submitted

I am using the following code to try and insert data into my database. The data works fine and i do this using a form. The form has a submit button that i will but the code in bellow the following code. I am using localhost to run my web application.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO PRODUCTS (P_Name, P_Description, P_Price) VALUES ('$_POST[Name]', '$_POST[description]', '$_POST[Price]' ) ";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
the submit button:
<div id="theSubmit">
<input type="submit" name="submit">
</div>
At the moment when i click submit i get taken to a page display the text New record created successfully. However I would like it to reload the page.
I am aware of the javascript location.reload(); is this what I have to use, if so where?
You should reload after execution of your sql like this.
$_SESSION['msg'] = "New record created successfully";
header("Location: $url"); // tell the client to load $url
exit(); // stop further execution of the current script
the $msg should be set via session to be able to show the msg after reload.
If you do it like that it is no problem if the user klicks the back button or do a page reload.
After reload do:
if(isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Use:
header("Location: $_SERVER[REQUEST_URI]");
exit;
This will redirect the user to the the same page using a GET method, reloading it.
If you are not displaying any DOM Elements, or doing any Header requests prior that PHP Script you can always use the php function
header('Location: your-url.com');
exit();
to reload a website.
if there are header requests prior that header function this solution wont work so you can add that JS code at the bottom of your script so it gets fired after you have dealt with the form.

Categories