Creating javascript function to destroy php session

◇◆丶佛笑我妖孽 提交于 2019-12-01 07:51:31

问题


I am having trouble figuring out how to create a javascript function that will destroy a php session. I have a clickable link that will call a function called destroyphpsess. I think this is all right so far. Now I need to define the javascript function. This is the code I have so far...

if ($_SESSION['color'] == "") {
    $var = "<a href='JavaScript:newPopup(\"http://www.yourfantasyfootballreality.com/register.php\");' class='two'>Register</a> | <a href='JavaScript:newPopup(\"http://www.yourfantasyfootballreality.com/signin.php\");' class='two'>Sign In</a>";
} else {
    $var = "Hello, ".$_SESSION['color'] ."! | " . "<a href=\"http://www.yourfantasyfootballreality.com/index.php\" onclick=\"destroyphpsess()\" class='two'>Log Out</a>";
}
echo $var;

Now I need to define the javascript function. This is where I am having trouble. This is the basic outline I have so far...

function destroyphpsess()
{
<?php
session_destroy();
?>
}

If someone could help me with the function I would appreciate it! Thanks.


回答1:


Your JavaScript runs client-side, and your PHP runs server-side. You can't call PHP functions from JavaScript this way. You have two options:

  1. Do an AJAX call to a server-side script that clears the session data (recommended, for consistency and proper clearing of that stuff server-side)
  2. Clear the PHPSESSID cookie with JavaScript (won't work if you reconfigure how you handle sessions, or if sessions are handled by URL parameters)



回答2:


A PHP session generally uses a cookie that is stored client side. The following code will clear that cookie thus unlinking the session.

document.cookie = 'PHPSESSID=; expires=Thu, 01-Jan-70 00:00:01 GMT;';




回答3:


Everyone keeps saying AJAX. This would be a good idea if you want to clean up the cookie on the server side as well, but I think if you knew what AJAX was you probably would have used it already...

I found AJAX pretty confusing when I first came across it. So what I would suggest is having a look at and maybe using jQuery's AJAX functionality. Including jQuery for just one function is probably overkill, but it might be a bit easier.




回答4:


Your JavaScript runs client-side, and your PHP runs server-side. You can't call PHP functions from JavaScript this way. You have two options:

Do an AJAX call to a server-side script that clears the session data (recommended, for consistency and proper clearing of that stuff server-side) Clear the PHPSESSID cookie with JavaScript (won't work if you reconfigure how you handle sessions, or if sessions are handled by URL parameters)



来源:https://stackoverflow.com/questions/11060735/creating-javascript-function-to-destroy-php-session

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