Search code examples
phpphp4

PHP: Pass a variable to a file you are including?


I am wondering if there is a way to pass a variable to a file you are including via include()?

I tried this but got an error:

include("header_alt.php?img=hey");

Is there a way to do that?

Thanks!


Solution

  • Just define your variable in the first file ; for instance, in temp.php :

    <?php
    $my_var = 10;
    
    include 'temp-2.php';
    
    die;
    ?>
    

    And use it in the second file ; temp-2.php :

    <?php
    
    var_dump($my_var);
    
    ?>
    

    And it should work : I'm getting this output, from temp-2.php :

    int 10
    


    The query-string syntax, using stuff like ?img=hey is used when you are requesting some data from a distant server (like when you are using your browser to surf on websites), not when including a file that is on the same server.