Sameer Sameer - 24 days ago 16
PHP Question

How to logout from session and cookies

I have symfony2 application.
I want to clear all session and cookies and logout application using controller. but after logingout when i click on back button in browser it returns application page instead of Login page.
In PHP

header
is used to redirect page but in symfony i dont know how to out this problem.
here is my code.

IndexAction

$session = $this->getRequest()->getSession();
$em = $this->getDoctrine()->getManager();
$user = new Loginsec();


if ($request->getMethod() == "POST") {
$session->clear();

$username = $request->get('user');
$password = $request->get('pass');
$remember = $request->get('remember');
if ($username != "" && $password != "") {
$Login = $this->checklogin($username, $password);
if ($Login) {

if ($remember != '') {
$response = new Response();
$cookiename = new Cookie('cookname',$username,time()+3600*24*7,'/LoginProject');

$response->headers->setcookie($cookiename);
$response->setContent($cookiename);
$response->send();
}


//Manage Session

$user->setUser($username);
$session->set('user',$username);
$session->start();

return $this->render('LoginLoginBundle:Default:Company.html.twig', array('name' => $session->get('user'));
} else {

return $this->render('LoginLoginBundle:Default:Login.html.twig', array('error' => 'Login Failed'));
}
} else {
return $this->render('LoginLoginBundle:Default:Login.html.twig', array('error' => 'Input required Fields'));
}
} else {

//Get SESSION
if ($session->has('user') && $session->has('pass')) {

$login = $this->checklogin($session->get('user'), $session->get('pass'));

if($login){
return $this->render('LoginLoginBundle:Default:Company.html.twig', array('name' => $session->get('user'));


}

}elseif($request->cookies->get('cookname')){

//Get Cookie
$request= $this->get('request');
$login = $this->checklogin($request->cookies->get('cookname'),$request->cookies->get('cookpass')) ;
if($login){
return $this->render('LoginLoginBundle:Default:Login.html.twig', array('error' => 'Login Using Cookie'));
}

} else {
return $this->render('LoginLoginBundle:Default:Login.html.twig');
}
}


logoutAction

Public function logoutAction(Request $request) {

$session = $this->getRequest()->getSession();
$session->clear('user');
$session->remove('user');
unset($session);

$response = new Response();
$response->headers->clearCookie('cookname') ;
$response->send();

return $this->render('LoginLoginBundle:Default:Login.html.twig');

}


Please help me if any Idea.

Answer

I was just reviewing my questions and found this one. Actually it's solved long time ago.

Unset session variable using

$session->remove('<Parameter>');

Ex.

$session->remove('user');
Comments