0

I have the following code:

<!DOCTYPE html>
<html lang="cs">
    <head>
        <title>Hardware audit - přihlášení</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="js/myPureScript.js"></script>
    </head>
    <body onload="setAutoSession">
        <?php
            if(file_exists("config.dat")){
                header('Location: login.php');
            }
            else{
                header('Location: setup.php');
            }
        ?>
    </body>
</html>

Part of myPureScript.js

function setAutoSession(){
    localStorage.setItem("username", "auto");
    console.log("nastavil jsem session"); // "I set the session"
}

The function setAutoSession is ignored, because I have log.console there and it is not displayed in my console. So where could be the problem. I think that only problem could be, that the PHP header is started before my function.

Thank you for your advice.

Michal Vlasák
  • 247
  • 2
  • 14
  • 1
    HTTP headers must be always sent at the beginning of a response. There is no way to output headers in the middle of the output. – Johann Bauer Jun 14 '16 at 08:22
  • Try: `` (Note the parentheses) – David Jun 14 '16 at 08:24
  • Come to think of it... What you're doing here doesn't even make sense. If you send a `Location` header, then the browser wouldn't need to load the `body` anyway. I'd expect this to result in an error from PHP. What is *actually* being sent to the client? What actually happens in the browser for you? – David Jun 14 '16 at 08:25
  • Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Epodax Jun 14 '16 at 08:48

1 Answers1

5

PHP is server side, and will be executed before page is rendered at client side. JavaScript will only execute when page loads, and by then PHP is already executed.

Additionally you should put header() before any html output

If your error reporting is on, you should get something like this I believe

Warning: Cannot modify header information - headers already sent by (output started at /whatever.php:1234) in /whatever.php on line 123
Vuk Stanković
  • 7,864
  • 10
  • 41
  • 65