Destroy a PHP session on clicking a link

别等时光非礼了梦想. 提交于 2019-12-04 03:29:58

No it is not a valid code. It will destroy the session at the time of loading the php page.

For destroying session on click you should write

<a href="logout.php" >Logout</a>

in logout.php

session_destroy();

Make a page called logout.php

Logout.php_____

<?php
Session_start();
Session_destroy();
header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Your page______

<a href="Logout.php">Logout</a>

Wrong code. you can use this code:

<?php if($_GET['logout']==1) session_destroy(); ?>
<a href="?logout=1">Logout</a>

That code will already destroy the session before clicking the link, you should do it like this:

HTML Page:

<a href="sessiondestroy.php">Logout</a>

Sessiondestroy.php :

<?=session_start(); session_destroy(); ?>

no its not valid...onclick is a client side event. you can do this instead.

     <a href="logout.php">logout</a>

and create a file called logout.php and include the session_destroy(); statement

       <?php
           session_destroy();

           //do other things... like redirect to a deafault/login page

         ?>

No, its not logical to call server-side function from client-side, onClick is an event occurs at client side, so, it cant call session_destroy()because it's server-side (PHP Function) which is not available at client side

It's possible to do that. If you are focused on using the onClick action, you could simply use AJAX. First you would have to create ajax.php, which would look like this:

<?php
//AJAX dynamic callback
if(isset($_GET['action'])){
    if($_GET['action'] == 'logout'){
        //destroy the session
        session_destroy();
        echo 'Logout success!';
        //redirect the user to a default web page using header
        header("location:http://example.com/");
    }
}
?>

Then you would want to create a javascript file that would tell ajax.php that you wanted to logout:

<script>
function logout()
 {
 var xmlhttp;
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("Logoutbutton").innerHTML=xmlhttp.responseText;
     }
   }
 xmlhttp.open("GET","ajax.php?action=logout",true);
 xmlhttp.send();
 }
</script>

Anyways, thanks for using StackOverflox, and please report back how it goes, or if you need additional help :)

TP

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!