php 写入会话从 1 页还是所有页开始?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7129498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:05:14  来源:igfitidea点击:

Write session start on 1 page or all pages?

phpmysqlsessionsession-variables

提问by hmwhat

All the tutorials say to put session start. They don't say if that should be in all pages on the website, or some, or only 1.

所有教程都说要开始会话。他们没有说这是否应该出现在网站的所有页面中,或者一些页面中,或者只有 1 个页面中。

And if it's only 1 page, does it have to be the main page? Or a page with a form that I am making that puts the session ID in the database? If the visitor never visits a page with a session id but they are on the site, do they still have a session id?

如果它只有 1 页,它是否必须是主页?或者我正在制作的带有将会话 ID 放入数据库的表单的页面?如果访问者从不访问带有会话 ID 的页面,但他们在网站上,那么他们还有会话 ID 吗?

回答by theprogrammer

You need to put this in each page that need to access the session data before accessing (or creating) any session data.

在访问(或创建)任何会话数据之前,您需要将它放在需要访问会话数据的每个页面中。

See: http://php.net/manual/en/function.session-start.php

请参阅:http: //php.net/manual/en/function.session-start.php

回答by Memochipan

Just for a matter of completeness you can choose to write session_start();in all pages, in just one or in none of them. Let me explain this.

出于完整性考虑,您可以选择session_start();在所有页面中书写,仅在其中一个页面中书写或在其中一个页面中都不书写。让我解释一下。

You need to start session in every script where you need access to $_SESSIONvariable but instead of putting session_start();in every single script you can create a file headers.php and put there all your repetitive code including session_start();

您需要在需要访问$_SESSION变量的每个脚本中启动会话,但session_start();您可以创建一个文件 headers.php 并将所有重复代码包括在内,而不是放入每个脚本中session_start();

If everything in your application needs access to $_SESSIONyou can forget the use of session_start();simply setting session.auto_start = 1in your php.ini file. You will be able to access $_SESSIONwithout writing session_start();before.

如果您的应用程序中的所有内容都需要访问,$_SESSION您可以忘记使用php.ini 文件中的session_start();简单设置session.auto_start = 1。您将$_SESSION无需写入即可访问session_start();

More here

更多在这里

回答by Shafiqul Islam

You need to declare session_start(); in every page if you want to get data from $_SESSION or store data into $_SESSION in those particular page. If you do not need to interact with $_SESSION then you don't have to declare session_start().@hmwhat

你需要声明 session_start(); 如果您想从 $_SESSION 获取数据或将数据存储到这些特定页面中的 $_SESSION 中,则在每个页面中。如果您不需要与 $_SESSION 交互,那么您不必声明 session_start().@hmwhat

回答by Alex

Anything that is going to access Session variables needs to start the session.

任何要访问会话变量的东西都需要启动会话。

So unless you have a php page that is non-dependent on the session than every page needs it.

因此,除非您有一个不依赖于会话的 php 页面,否则每个页面都需要它。