ScotlandPHP 2016


(PHP 4, PHP 5, PHP 7)

session_destroyDestrói todos os dados registrados em uma sessão


bool session_destroy ( void )

session_destroy() destrói todos os dados associados com a sessão atual. Ela não apaga nenhuma das variáveis globais associadas a sessão atual, nem apaga o cookie de sessão. Para usar as variáveis de sessão novamente, session_start() tem que ser chamada.

Para matar a sessão também, como para fazer o log out do usuário, o id da sessão também deve ser apagado. Se um cookie for usado para propagar o id de sessão (funcionamento padrão), então o cookie de sessão deve ser excluído. setcookie() pode ser usado para isso.

Valor Retornado

Retorna TRUE em caso de sucesso ou FALSE em caso de falha.


Exemplo #1 Destruindo uma sessão com $_SESSION

// Inicializa a sessão.
// Se estiver sendo usado session_name("something"), não esqueça de usá-lo agora!

// Apaga todas as variáveis da sessão
$_SESSION = array();

// Se é preciso matar a sessão, então os cookies de sessão também devem ser apagados.
// Nota: Isso destruirá a sessão, e não apenas os dados!
if (ini_get("session.use_cookies")) {
$params session_get_cookie_params();
setcookie(session_name(), ''time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]

// Finalmente, destrói a sessão



Somente use session_unset() para código antigo/obsoleto que não use $_SESSION.

Veja Também

add a note add a note

User Contributed Notes 4 notes

Praveen V
3 years ago
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.


[Edited by moderator (googleguy at php dot net)]
Jack Luo
2 years ago
It took me a while to figure out how to destroy a particular session in php. Note I'm not sure if solution provided below is perfect but it seems work for me. Please feel free to post any easier way to destroy a particular session. Because it's quite useful for functionality of force an user offline.

1. If you're using db or memcached to manage session, you can always delete that session entry directly from db or memcached.

2. Using generic php session methods to delete a particular session(by session id).

= 'nill2if998vhplq9f3pj08vjb1';
// 1. commit session if it's started.
if (session_id()) {

// 2. store current session id
$current_session_id = session_id();

// 3. hijack then destroy session specified.

// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!

9 years ago
Note that when you are using a custom session handler, session_destroy will cause a fatal error if you have set the session destroy function used by session_set_save_handler to private.

Fatal error: Call to private method Session::sessDestroy()

where sessDestroy was the function I specified in the 5th parameter of session_set_save_handler.

Even though it isn't all that desirable, the simple solution is to set sessDestroy to public.
administrator at anorhack dot com
9 years ago
Destroying  a session from a background job

I have a thief-protection system that compares country codes from login IPs via whois. This has to run in the background as it is way too processor-hungry to be run in the browser.

What I needed was a way to destroy the web session from the background job. For some reason, a background session_destroy APPEARS to work, but doesnt't actually destroy the web session.

There is a work around, I set the username to NULL and the web code picks up on that, bouncing the user (thief) to a "gotcha" page where his IP is logged.

Yes I know its nasty and dirty, but surprisingly it works.

$sid = the session_id() of the suspicious web session, passed in $argv to the background job

The trick is to "stuff" the $_GET array with the sid, then the session_start in the background job picks this value up (as if it were a genuine trans-sid type thing...?PHPSESSID=blah) and "connects to" the web session. All $_SESSION variable can be viewed (and CHANGED , which is how this kludge works) but for some reason (that no doubt someone will illuminate) they can't be unset...setting the particular variable to NULL works well though:

// prove we are getting the web session data
foreach($_SESSION as $k => $v) echo($k."=".$v);
// now kill the thief
//web session variable now NULL - honestly!
To Top