I am working on a school project where I need my .php pages communicating. I have header.php where I set connection to the database and start the session. In order to start the session only once, I've used this:
我正在开展一个学校项目,我需要将.php页面进行通信。我有header.php,我在其中设置与数据库的连接并启动会话。为了只启动一次会话,我使用了这个:
if(session_id() == '') {
session_start();
}
PHP version is PHP 5.3.10-1 ubuntu3.18 with Suhosin-Patch (cli)
PHP版本是PHP 5.3.10-1 ubuntu3.18与Suhosin-Patch(cli)
I am trying to pass some $_SESSION variables between pages, but they keep being unset when I try to use them on a page that doesn't set them. I see many people have complained about this, but I still can't find the solution.
我试图在页面之间传递一些$ _SESSION变量,但是当我尝试在没有设置它们的页面上使用它们时它们一直未设置。我看到很多人抱怨这个,但我仍然找不到解决方案。
login-form.php
<?php
if (isset($_SESSION["login-error"])) {
echo '<p>'.$_SESSION["login-error"].'</p>';
}
?>
login.php
$_SESSION["login-error"]= "Username or password incorrect";
There is a code snippet of what is not working for me. Thanks
有一段不适用于我的代码片段。谢谢
4 个解决方案
#1
You can try this.
你可以试试这个。
In your function file put this
在你的函数文件中放这个
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
Then you can run this in every page you want session started
然后,您可以在希望会话启动的每个页面中运行此功能
if ( is_session_started() === FALSE ) session_start();
With this I think you should be good to go on starting your session across pages. Next is to ensure you set a session to a value. If you are not sure what is unsetting your sessions you can try var_dump($_SESSION)
at different parts of your code so you be sure at what point it resets then know how to deal with it.
有了这个,我认为你应该很好地开始跨页面的会话。接下来是确保将会话设置为值。如果你不确定你的会话是什么,你可以在你的代码的不同部分尝试var_dump($ _ SESSION),这样你就可以确定它在什么时候重置然后知道如何处理它。
#2
The variables are probable not set, because you haven't activate the session variables with session_start().
变量可能未设置,因为您尚未使用session_start()激活会话变量。
session_id() == ''
is not a correct conditional . Use instead:
session_id()==''不是正确的条件。改为使用:
if (!isset($_SESSION)) { session_start();}
if you have session started then you can set a session variable
如果您已启动会话,则可以设置会话变量
if (!isset($_SESSION["login-error"])) { $_SESSION["login-error"]= "Username or password incorrect";}
Before you call $_SESSION["login-error"], type session_start()
, just for testing, to find when the session signal is missing. You said
在调用$ _SESSION [“login-error”]之前,键入session_start(),仅用于测试,以查找会话信号何时丢失。你说
PHP $_SESSION variables are not being passed between pages
PHP $ _SESSION变量不在页面之间传递
session_start() and SESSION variables needs to be included at the beginning of EVERY page or at the place where SESSION variables are being called (through a common file, bootstrap, config or sth) at the beginning of EVERY page. ie the command to read those data from the server is needed.
session_start()和SESSION变量需要包含在每个页面的开头或者每个页面开头调用SESSION变量的地方(通过公共文件,bootstrap,config或sth)。即需要从服务器读取这些数据的命令。
#3
Since my header.php file included "connection.php" file, I put
由于我的header.php文件包含“connection.php”文件,我把
session_start();
at the beginning of connection.php and deleted it from header.php file. Now it works fine. Thanks all for your help!
在connection.php的开头,从header.php文件中删除它。现在它工作正常。感谢你的帮助!
#4
PHP sessions rely on components of HTTP, like Cookies and GET variables, which are clearly not available when you're calling a script via the CLI. You could try faking entries in the PHP superglobals, but that is wholly inadvisable. Instead, implement a basic cache yourself.
PHP会话依赖于HTTP的组件,如Cookie和GET变量,当您通过CLI调用脚本时,这些变量显然不可用。您可以尝试伪造PHP超级全局中的条目,但这是完全不可取的。而是自己实现基本缓存。
<?php
class MyCache implements ArrayAccess {
protected $cacheDir, $cacheKey, $cacheFile, $cache;
public function __construct($cacheDir, $cacheKey) {
if( ! is_dir($cacheDir) ) { throw new Exception('Cache directory does not exist: '.$cacheDir); }
$this->cacheDir = $cacheDir;
$this->cacheKey = $cacheKey;
$this->cacheFile = $this->cacheDir . md5($this->cacheKey) . '.cache';
// get the cache if there already is one
if( file_exists($this->cacheFile) ) {
$this->cache = unserialize(file_get_contents($this->cacheFile));
} else {
$this->cache = [];
}
}
// save the cache when the object is destructed
public function __destruct() {
file_put_contents($this->cacheFile, serialize($this->cache));
}
// ArrayAccess functions
public function offsetExists($offset) { return isset($this->cache[$offset]); }
public function offsetGet($offset) { return $this->cache[$offset]; }
public function offsetSet($offset, $value) { $this->cache[$offset] = $value; }
public function offsetUnset($offset) { unset($this->cache[$offset]); }
}
$username = exec('whoami');
$c = new MyCache('./cache/', $username);
if( isset($c['foo']) ) {
printf("Foo is: %s\n", $c['foo']);
} else {
$c['foo'] = md5(rand());
printf("Set Foo to %s", $c['foo']);
}
Example runs:
# php cache.php
Set Foo to e4be2bd956fd81f3c78b621c2f4bed47
# php cache.php
Foo is: e4be2bd956fd81f3c78b621c2f4bed47
This is pretty much all PHP's sessions do, except a random cache key is generated [aka PHPSESSID] and is set as a cookie, and the cache directory is session.save_path
from php.ini
.
这几乎都是PHP的会话,除了生成随机缓存键[又名PHPSESSID]并设置为cookie,缓存目录是来自php.ini的session.save_path。
#1
You can try this.
你可以试试这个。
In your function file put this
在你的函数文件中放这个
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
Then you can run this in every page you want session started
然后,您可以在希望会话启动的每个页面中运行此功能
if ( is_session_started() === FALSE ) session_start();
With this I think you should be good to go on starting your session across pages. Next is to ensure you set a session to a value. If you are not sure what is unsetting your sessions you can try var_dump($_SESSION)
at different parts of your code so you be sure at what point it resets then know how to deal with it.
有了这个,我认为你应该很好地开始跨页面的会话。接下来是确保将会话设置为值。如果你不确定你的会话是什么,你可以在你的代码的不同部分尝试var_dump($ _ SESSION),这样你就可以确定它在什么时候重置然后知道如何处理它。
#2
The variables are probable not set, because you haven't activate the session variables with session_start().
变量可能未设置,因为您尚未使用session_start()激活会话变量。
session_id() == ''
is not a correct conditional . Use instead:
session_id()==''不是正确的条件。改为使用:
if (!isset($_SESSION)) { session_start();}
if you have session started then you can set a session variable
如果您已启动会话,则可以设置会话变量
if (!isset($_SESSION["login-error"])) { $_SESSION["login-error"]= "Username or password incorrect";}
Before you call $_SESSION["login-error"], type session_start()
, just for testing, to find when the session signal is missing. You said
在调用$ _SESSION [“login-error”]之前,键入session_start(),仅用于测试,以查找会话信号何时丢失。你说
PHP $_SESSION variables are not being passed between pages
PHP $ _SESSION变量不在页面之间传递
session_start() and SESSION variables needs to be included at the beginning of EVERY page or at the place where SESSION variables are being called (through a common file, bootstrap, config or sth) at the beginning of EVERY page. ie the command to read those data from the server is needed.
session_start()和SESSION变量需要包含在每个页面的开头或者每个页面开头调用SESSION变量的地方(通过公共文件,bootstrap,config或sth)。即需要从服务器读取这些数据的命令。
#3
Since my header.php file included "connection.php" file, I put
由于我的header.php文件包含“connection.php”文件,我把
session_start();
at the beginning of connection.php and deleted it from header.php file. Now it works fine. Thanks all for your help!
在connection.php的开头,从header.php文件中删除它。现在它工作正常。感谢你的帮助!
#4
PHP sessions rely on components of HTTP, like Cookies and GET variables, which are clearly not available when you're calling a script via the CLI. You could try faking entries in the PHP superglobals, but that is wholly inadvisable. Instead, implement a basic cache yourself.
PHP会话依赖于HTTP的组件,如Cookie和GET变量,当您通过CLI调用脚本时,这些变量显然不可用。您可以尝试伪造PHP超级全局中的条目,但这是完全不可取的。而是自己实现基本缓存。
<?php
class MyCache implements ArrayAccess {
protected $cacheDir, $cacheKey, $cacheFile, $cache;
public function __construct($cacheDir, $cacheKey) {
if( ! is_dir($cacheDir) ) { throw new Exception('Cache directory does not exist: '.$cacheDir); }
$this->cacheDir = $cacheDir;
$this->cacheKey = $cacheKey;
$this->cacheFile = $this->cacheDir . md5($this->cacheKey) . '.cache';
// get the cache if there already is one
if( file_exists($this->cacheFile) ) {
$this->cache = unserialize(file_get_contents($this->cacheFile));
} else {
$this->cache = [];
}
}
// save the cache when the object is destructed
public function __destruct() {
file_put_contents($this->cacheFile, serialize($this->cache));
}
// ArrayAccess functions
public function offsetExists($offset) { return isset($this->cache[$offset]); }
public function offsetGet($offset) { return $this->cache[$offset]; }
public function offsetSet($offset, $value) { $this->cache[$offset] = $value; }
public function offsetUnset($offset) { unset($this->cache[$offset]); }
}
$username = exec('whoami');
$c = new MyCache('./cache/', $username);
if( isset($c['foo']) ) {
printf("Foo is: %s\n", $c['foo']);
} else {
$c['foo'] = md5(rand());
printf("Set Foo to %s", $c['foo']);
}
Example runs:
# php cache.php
Set Foo to e4be2bd956fd81f3c78b621c2f4bed47
# php cache.php
Foo is: e4be2bd956fd81f3c78b621c2f4bed47
This is pretty much all PHP's sessions do, except a random cache key is generated [aka PHPSESSID] and is set as a cookie, and the cache directory is session.save_path
from php.ini
.
这几乎都是PHP的会话,除了生成随机缓存键[又名PHPSESSID]并设置为cookie,缓存目录是来自php.ini的session.save_path。