简体   繁体   English

将$ _SESSION变量传递到包含的文件

[英]Pass $_SESSION variables to included file

i have a first PHP file: /home/www/subdomain1.domain.tld/file.php 我有第一个PHP文件:/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: 和/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? 我认为第一个文件中的“ include”会生成“ 500 Internal Server Error”,这是因为会话变量未传递给包含的文件,我该如何解决?

Thank you Alex 谢谢亚历克斯

EDIT: I must use session variables in order to use these variables on every php file on subdomain2. 编辑:我必须使用会话变量,以便在subdomain2的每个PHP文件上使用这些变量。

You don't need to use sessions when including a file. 包含文件时无需使用会话。 It is all the same request with the same namespace. 具有相同名称空间的请求都是相同的。

file.php: file.php:

$foo = 'bar';

include 'foo2.php';

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. 由于会话是在file.php中启动的,因此foo2.php已经可以使用它。

The error may be because PHP output a warning that the session was already started. 该错误可能是因为PHP输出警告,表明该会话已经启动。

For debugging, add error_reporting(E_ALL); ini_set('display_errors', 1); 要进行调试,请添加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. 到第一个PHP脚本的开头。

You should just be able to do: 您应该能够:

file.php file.php

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

foo2.php foo2.php

i have a first PHP file: /home/www/subdomain1.domain.tld/file.php 我有第一个PHP文件:/home/www/subdomain1.domain.tld/file.php

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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