It doesn't look like you have a framework going, so I think there are some general tips to help your script succeed.
1) Have a top-level config file in your site root that you include at the top of all your MAIN pages:
/config.php
<?php
# Create some helpful constants
define('ROOT_DIR',__DIR__);
define('DS',DIRECTORY_SEPARATOR);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('BASE_URL','http://www.example.com');
# This includes our function loader (see below)
include_once(FUNCTIONS.DS.'loadFunc.php');
# Load the getSession() function (see below)
loadFunc('getSession');
# Start session here
session_start();
2) Then create some helpful functions (I would learn Object Oriented Programming instead so you can use a framework effectively, but functions are better than nothing):
/functions/loadFunc.php
function loadFunc($name)
{
if(!is_array($name))
$name = array($name);
foreach($name as $func) {
# If the function is already loaded, skip
if(function_exists($func))
continue;
# See if the function file exists
if(is_file($file = FUNCTIONS.DS.$func.'.php'))
include_once($file);
}
}
}
/functions/getSession.php
function getSession($key=false,$clear=false)
{
# If requesting a specific value return that
if(!empty($key)) {
# Get value
$value = (isset($_SESSION[$key]))? $_SESSON[$key] : false;
# If the key is set and clear is set, clear the value
if(isset($_SESSON[$key]) && $clear) {
unset($_SESSON[$key]);
}
# Return session value
return $value;
}
# No key set, return full session
return $_SESSION;
}
/functions/setSession.php
function setSession($key,$value)
{
$_SESSION[$key] = $value;
}
/functions/redirect.php
function redirect($to,$exit=true)
{
header("Location: {$to}");
# You should exit on redirect
if($exit)
exit;
}
3) Now, when you go to create a page, you include this config ONCE at the top of the page:
/students.php
<?php
# Now that you include this, you know session is always set
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Get the key msg from the session and use parameter #2 to clear the session key
$msg = getSession('msg',true);
# It's not empty, write message
if($msg): ?>
<div class="msg">
<?php echo $msg ?>
</div>
<?php endif ?>
/server.php
<?php
# Include config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Load our two required functions
loadFunc(array('setSession','redirect'));
# You have to determine either message here, not both.
# Using pseudo-code here to demonstrate
if($add) {
# Use function to set session value
setSession('msg',"New student saved");
}
elseif($update) {
setSession('msg',"Information updated");
}
# Since both use the same redirect, you only need it once
redirect('students.php');
So, if you delete all your session_start()
in all your files except for the config and then always include the config on the top-level page at the top, you won't run into errors for the session.