简体   繁体   中英

Where do I put session_start function?

I'm fairly new to PHP and I'm trying to work out the best place in my current scenario to place the session_start() function.

I'm currently making website and the first page to load is index.php which requires db.php to connect to a MySQL database, and only contains an html form for logging in and pushes an error message when the details are invalid.

When the user enters the username & password, the data is passed to checklogin.php , where prepared statements are used and if the data matches then $_SESSION['username'] is called and the user is redirected to portal.php . (If there is no match, it redirects to index.html with an error message now visible.)

My question is, should session_start() be placed at the beginning of index.php (code mainly in html, uses php only to require 'db.php'; , to connect to the database and to push the error message if credentials don't match).

Or, should I use it at the beginning of checklogin.php (where $_SESSION['data'] is used for the first time)?

The session_start() function must be the very first thing in your document. Before any HTML tags.

Every page that will use the session information on the website must be identified by the session_start() function. This initiates a session on each PHP page. The session_start function must be the first thing sent to the browser or it won't work properly. It must precede any HTML tags. Usually, the best place to position it is right after the <?php tag. It must be on every page you intend to use.

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