问题
Is this code valid?
<a href="#" onclick="<?php session_destroy();?>">Logout</a>
回答1:
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();
回答2:
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>
回答3:
Wrong code. you can use this code:
<?php if($_GET['logout']==1) session_destroy(); ?>
<a href="?logout=1">Logout</a>
回答4:
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(); ?>
回答5:
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
?>
回答6:
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
回答7:
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
来源:https://stackoverflow.com/questions/17564795/destroy-a-php-session-on-clicking-a-link