Michal Vlasák
Michal Vlasák

Reputation: 247

php header javascript what goes first?

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.

Upvotes: 0

Views: 281

Answers (1)

Vuk Stanković
Vuk Stanković

Reputation: 7954

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

Upvotes: 5

Related Questions