Write session start on 1 page or all pages?

2019-02-03 06:12发布

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.

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?

4条回答
迷人小祖宗
2楼-- · 2019-02-03 06:38

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.

You need to start session in every script where you need access to $_SESSION variable 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();

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

More here

查看更多
爷的心禁止访问
3楼-- · 2019-02-03 06:41

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

查看更多
时光不老,我们不散
4楼-- · 2019-02-03 06:46

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.

查看更多
smile是对你的礼貌
5楼-- · 2019-02-03 06:47

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

查看更多
登录 后发表回答