0

I have this login.php and a javascript to sync the date and time from the client browser to the server of my openwrt router. What I want is, every time a user successfully logs in, it'll execute that javascript and then redirect to status.php which is the home page. Here's what I've tried so far

if ($_POST['username'] == $user[0] && $_POST['password'] == $pass[0]) {
        $_SESSION['loggedin'] = 1;
        echo '<script src="date.js"></script>';
        header("Location: status.php");
        exit;
    }

But it gives me this error:

Warning: Cannot modify header information - headers already sent by (output started at /www/login.php:10) in /www/login.php on line 11

How do I fix it ?

Some of you may think my question is a duplicate but please understand that I need to execute that javascript after successful login.

hillz
  • 537
  • 6
  • 10
  • 18
  • 2
    Possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – tkausl Jun 24 '16 at 02:29

3 Answers3

1

The problem is that you cannot send the header after echoing. To solve this, ob_start is used to turn output buffering on which means when using echo, no output is sent but instead it is stored in an internal buffer and when we call ob_end_flush after we have called header(), the internal buffer contents will be flushed and output buffering will stop.

Try:

ob_start();
echo '<script src="date.js"></script>';
header("Refresh: 5; url=status.php");
ob_end_flush();

Hope this helps.

Osama Sayed
  • 1,993
  • 15
  • 15
  • I tried that but the javascript doesn't get executed. It just gets me straight to `status.php` without syncing the date and time. – hillz Jun 24 '16 at 02:32
  • @hillz Okay you can refresh after like 5 second to give time to js to execute. I will edit my answer. – Osama Sayed Jun 24 '16 at 02:35
0

you can't put header.. after "echo .." or other html element ..

why you need to put your date.js ?

if ($_POST['username'] == $user[0] && $_POST['password'] == $pass[0]) {
    $_SESSION['loggedin'] = 1;
 //   echo '<script src="date.js"></script>';
    header("Location: status.php");
    exit;
}
Amazone
  • 426
  • 4
  • 14
0

put you JavaScript code out side your php code , open your php code and before your JavaScript code close the php put your JavaScript code normally without echo after that put the begin and end tags for php