Logout +8 php session-cookie...">

Destroy a PHP session by clicking a link

Is this code valid?

<a href="#" onclick="<?php session_destroy();?>">Logout</a> 
+8
source share
7 answers

No, this is an invalid code. It will destroy the session while loading the php page.

To destroy a session on click, you must write

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

in logout.php

 session_destroy(); 
+14
source

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> 
+14
source

Incorrect code. you can use this code:

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

This code will already destroy the session before clicking on the link, you should do it as follows:

HTML page:

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

Sessiondestroy.php:

 <?=session_start(); session_destroy(); ?> 
+4
source

no its invalid ... onclick is a client-side event. You can do it instead.

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

and create a file called logout.php and enable session_destroy (); Statement

  <?php session_destroy(); //do other things... like redirect to a deafault/login page ?> 
+3
source

No, it’s not logical to call a server function on the client side, onClick - this event occurs on the client side, therefore it cannot call session_destroy() , because it is a server (PHP function), which is not accessible on the client side

+2
source

It can be done. If you focus on using the onClick action, you can just use AJAX. First you will need to create ajax.php, which will 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 need to create a javascript file that tells ajax.php that you want to log out:

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

Anyway, thanks for using StackOverflox and let me know how this happens, or if you need more help :)

TR

+1
source

Source: https://habr.com/ru/post/949088/


All Articles