0

Login code and if successful, a header redirect is implemented. It works at random times, I don't know what I'm doing to get it working and then for it to fail.

 <?php
ob_start();
require ("include/PassHash.php");  

if(isset($_POST['login'])){

    // Returns more than 0 rows (Email found)
    if($total>0 && PassHash::check_password($row['password'], $_POST['password'])){     
        // Correct credentials.
        $_SESSION['user_id'] = $row['id'];
        $_SESSION['user_email'] = $email;
        session_set_cookie_params(24*60*60);
        header("Location: /index.php?p=user_account");
        exit();
        ob_end_flush();
    } else {
        // Incorrect password / email.

    }
}
?>
  • why do you use ob_start and ob_end_flush (gets never executed tho)? What happens when you remove them? – Green Black Jan 29 '13 at 21:10
  • I've read about them in a few tutorials so I thought I'd try them. Again, Headers already sent error appears. –  Jan 29 '13 at 21:11
  • You have leading spaces or output before your code. – datasage Jan 29 '13 at 21:13
  • than that is your problem probably. First find where the whitespace is (in your post a space is before – Green Black Jan 29 '13 at 21:14
  • If you have any echos or HTML code above header(), it will NOT work and you will get "headers already sent". – UnholyRanger Jan 29 '13 at 21:15
  • @John, There isn't any code above the –  Jan 29 '13 at 21:29
  • Yes, you cannot output something (the html in header.php) and than sent headers later. That is your problem. – Green Black Jan 29 '13 at 21:35
  • 1
    See http://stackoverflow.com/questions/8028957/headers-already-sent-by-php for workarounds and causes for random failures, in particular with ob_start. – mario Jan 29 '13 at 21:35
  • @John, but then as my site is dynamic, so I have an index.php which includes the pages then I call them from /index.php?p=..... then Headers() are impossible to use? –  Jan 29 '13 at 21:37
  • read the link @mario posted. Sure you can use them. – Green Black Jan 29 '13 at 21:40
  • @John, by the looks of that I'll have the use the meta refresh! –  Jan 29 '13 at 21:43

1 Answers1

0

In php, if you are writing any code that involves sessions or headers, you need to be careful about preventing any output before the code is called. Once output is sent, the response headers also get sent and you wont be able to change them.

Output can be anything from echo/print statements, but more commonly, its leading spaces or linebreaks before your PHP code. You need to have the <?php open tag to start on the first line and first character of the file.

datasage
  • 19,153
  • 2
  • 48
  • 54