Search code examples
phpif-statementsessionheaderinclude

can sessions take part in the include function?


I got 3 files: index.php / header.php and footer.php

I want the session go ahead of header.php

index.php

<?php include("header.php"); ?>
// Some Data inside index.php
<?php include("footer.php"); ?>

header.php

<?php if(session('access_token')) { ?>

footer.php

<?php } ?>

how can I make this method gonna work? I need the session start on header.php but dont wanna close him there!


Solution

  • You can set PHP Session's in any file, as long as you always have them started, so ensure that you include header.php in all of your files that you want to protect.

    Your header.php should include:

    <?php
    
    //Start PHP session if not already started
    if(session_id() == '') {
        session_start();
    }
    
    ?>
    

    Your index,php file could include something like this:

    <?php
    
    /* Include header */
    require("header.php");
    
    if(isset($_SESSION["access_token"])){
       /* Content only if the access token is in session */
    } else {
       die("Access token not found");
    }
    
    /* Include footer */
    include("footer.php");
    
    ?>
    

    As for your footer.php, this shouldn't affect any of the above PHP code or alter the outcome of what you are trying to achieve.