The scope of $_SESSION

I have a simple little homework page. It begins with an index.php, which points directly at startfile.html.php

At the top of startfile.html.php I start a $_SESSION array

<?php session_start(); $_SESSION['error'] = 'So far everything is OK.'; ?>

I thought this was a global array, available to all webpages beneath startfile.html.php i.e. all my folders and webpages.

However, when I do not have session_start(); at the top of, say change_PW_form.php I do not see the error messages from $_SESSION.

For instance:
if($password != $confirm){
//return the values to the user
$_SESSION[‘email’] = $email;
//display error
$_SESSION[‘PWerror’] = ‘密码不一样 Passwords did not match’;
include ‘changePW_form.php’;

If I enable session_start(); at the top of all my pages, I see all the error or success messages.

BUT, then I constantly get error messages in the error_log file like this:

[Sun Feb 28 11:05:39 2021] [warn] [client] mod_fcgid: stderr: PHP Notice: A session had already been started - ignoring session_start() in /var/www/vhosts/ on line 3, referer:

What can I do to stop these error_log messages, but keep my problem or success info messages??

Maybe I need to declare a default value for all possible $_SESSION values right at the start, not per folder and webpage??

$_SESSION variables are available throughout the ‘currently’ executing script, which would include files that are ‘required’ (you should use require for files that your script must have for it to work) through the filesystem by the currently executing script and any additional (nested) require statements in the required files. $_SESSION variables persist between different http(s) requests when a successful session_start() statement is executed.

Each web page needs one session_start() statement. The error you are getting occurs when there is more than one, which would indicate that your main .php file contains one and the file being included (should use require) also contains one.

The symptom you are getting is likely (it would take seeing all the code needed to reproduce the problem) because you are both including a file and causing a http(s) request to the same file, such as redirecting to it, using it as the action in a form tag, or in a link.


So my toplevel file is: startfile.html.php with the PHP:

<?php session_start(); $_SESSION['error'] = 'So far everything is OK.'; ?>

I should put require (or include???) statements for each file used below it? Like:

 <?php session_start(); $_SESSION['error'] = 'So far everything is OK.'; 
require '/19BEcw/changePW_form.php'
require  '/20BEcw/changePW_form.php'
// and quite a few more ...

No. Nothing I wrote had anything to do with making changes to your code. I listed one likely cause, based on the symptoms, that has to be either confirmed or disproven as the source of the problem. You have to find what’s causing a problem before you can fix it.

Sponsor our Newsletter | Privacy Policy | Terms of Service