Jerome
Jerome

Reputation: 139

header location php issues

Here's my code, that works on localhost and redirect me to the login page:

require("common.php"); 

unset($_SESSION['user']); 
 session_destroy(); 

header("Location: login.php"); 

But when I upload it to my web server, the header is not sent. User is not redirected to my login page when he logs in. But the session was already started.

Here's the code:

require("common.php"); 


$submitted_username = ''; 


if(!empty($_POST)) 
{ 

    $query = " 
        SELECT 
            id, 
            username, 
            password, 
            salt, 
            email 
        FROM users 
        WHERE 
            username = :username 
    "; 


    $query_params = array( 
        ':username' => $_POST['username'] 
    ); 

    try 
    { 

        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 

        die("Failed to run query: " . $ex->getMessage()); 
    } 


    $login_ok = false; 


    $row = $stmt->fetch(); 
    if($row) 
    { 

        $check_password = hash('sha256', $_POST['password'] . $row['salt']); 
        for($round = 0; $round < 65536; $round++) 
        { 
            $check_password = hash('sha256', $check_password . $row['salt']); 
        } 

    if($check_password === $row['password'])
        { 
            $login_ok = true; 
        } 
      if($login_ok) 
    { 

        unset($row['salt']); 
        unset($row['password']); 


        $_SESSION['user'] = $row; 

     header("Location:form_menu.php"); 

    } 
    else 
    { 

        echo("<font color=red>Login Failed. Icorrect Password </font>"); 


        $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); 
    }

    }
}

How to resolve this problem? Is there a problem with my web server?

Upvotes: 1

Views: 1808

Answers (2)

Mrinmoy Ghoshal
Mrinmoy Ghoshal

Reputation: 2834

At the top of page add

     ob_start();

And the Bottom of Page add

    ob_end_flush();

I hope it will work.

A header in PHP always run before any output occurs, so turn on output buffering.

Upvotes: 1

MrTechie
MrTechie

Reputation: 1847

You are asking to session_destroy() but you have no session_start() in your code unless it's in your common.php. And I always make sure I exit; after a header("Location: xxx.php");

So try this, change this:

<?php 

require("common.php"); 

unset($_SESSION['user']); 
 session_destroy(); 

header("Location: login.php"); 


?>

to this:

<?php 
 session_start();

   require("common.php"); 

    unset($_SESSION['user']); 
    session_destroy(); 

    header("Location: login.php"); 
    exit;


?>

And then add this to the top of your other code just after the opening

session_start();

Upvotes: 1

Related Questions