简体   繁体   中英

Pass $_SESSION variables to included file

i have a first PHP file: /home/www/subdomain1.domain.tld/file.php

<?php
    session_start();
    $_SESSION['foo']='bar';   
    include "/home/www/subdomain2.domain.tld/foo2.php";
 ?>

and /home/www/subdomain2.domain.tld/foo2.php:

<?php 
    session_start();
    echo $_SESSION['foo'];
?>

The "include" in the first file generates a "500 Internal Server Error", i think it's because session variables are not passed to included files, how can i fix that?

Thank you Alex

EDIT: I must use session variables in order to use these variables on every php file on subdomain2.

You don't need to use sessions when including a file. It is all the same request with the same namespace.

file.php:

$foo = 'bar';

include 'foo2.php';

foo2.php

echo $foo; // returns 'bar'

You shouldn't be starting the session in the second file. Since the session was started in file.php, it is already available to foo2.php.

The error may be because PHP output a warning that the session was already started.

For debugging, add error_reporting(E_ALL); ini_set('display_errors', 1); error_reporting(E_ALL); ini_set('display_errors', 1); to the beginning of your first PHP script.

You should just be able to do:

file.php

<?php
    session_start();
    $_SESSION['foo']='bar';   
    include "/home/www/subdomain2.domain.tld/foo2.php";

foo2.php

i have a first PHP file: /home/www/subdomain1.domain.tld/file.php

and /home/www/subdomain2.domain.tld/foo2.php:

<?php 
// session_start();  // remove, do not need this here
echo $_SESSION['foo'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM