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.

4
  • 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. Commented Jun 14, 2016 at 8:22
  • Try: <body onload="setAutoSession()"> (Note the parentheses) Commented Jun 14, 2016 at 8: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? Commented Jun 14, 2016 at 8:25
  • Possible duplicate of What is the difference between client-side and server-side programming? Commented Jun 14, 2016 at 8:48

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.