Skip to content
Advertisement

Not being redirected to a page after destroying session in php

I am having an issue when it comes to redirection.

What I have done is a var dump to see the values for $_SESSION[reset-password-page]. I can see when I am on a previous page and submit a form, the $_SESSION[reset-password-page] is set to reset-password, which is great it’s what I want.

Now I what I try to do is destroy the session at the end of the page. The purpose of this is that if the user refreshes the page, the session has already been destroyed and so they sohuld be redirected back to the login page.

I can see the value for $_SESSION[reset-password-page] in my var dump is set to NULL, but it doesn’t redirect me, i stay on the same page.

Can I ask how to solve this so I can be redirected?

<?php
session_start();

echo var_dump($_SESSION['reset-password-page']);

if(isset($_SESSION['reset-password-page']))
  if ($_SESSION['reset-password-page'] != "reset-password") {
  
   header("location: login");
  
   }
?>

        <html>
        <head></head>
        <body>
            
        <div style="text-align: center; margin-top: 2em;">

        <img src="static/images/logo.png">
            
        <h2>TITLE</h2>
        
        <p class='success-msg'><i class='fa fa-check'></i> View your email to retrieve your new access code</p>
        
        <p><a href="login" class="linkcss" style="width:auto;"><b>Back To Online Course</b></a></p>

        </div>
        
        </body>
        </html>
        

<?php

   session_destroy();
 
?>

Advertisement

Answer

To start with, delete echo var_dump($_SESSION['reset-password-page']);. This is output and will stop headers from working properly (see here for why).

Also you don’t actually redirect when the session is empty. If there is no session, if(isset($_SESSION['reset-password-page'])) will be false and so won’t run the block which includes your header redirect code. You probably want an else that also redirects.

Alternatively, you could try something like if (!isset($_SESSION['reset-password-page']) || $_SESSION['reset-password-page'] != 'reset-password') instead of both those if statements which will redirect if the session key’s value is null or it’s not null but also not reset-password.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement