I’m building a system that captures info from a POST
method and adds them into a PHP $_SESSION
. The basic logic I want to follow is:
- Check the method and call the relevant function
- Check if
$_SESSION
data already exists via a function - Check if the
$post_id
variable is already in the$_SESSION
's array via a function - Based on the outcomes on these functions, add to the array, create a new array, or do nothing
Here is the code I have written to handle this logic so far. I am looking to get just the add_to_lightbox()
function working first, and will move onto the other two after.
session_start();
// set variables for the two things collected from the form
$post_id = $_POST['id'];
$method = $_POST['method'];
// set variable for our session data array: 'ids'
$session = $_SESSION['ids'];
if ($method == 'add') {
// add method
add_to_lightbox($post_id, $session);
} elseif ($method == 'remove') {
// remove method
remove_from_lightbox($post_id);
} else ($method == 'clear') {
// clear method
clear_lightbox();
}
function session_exists($session) {
if (array_key_exists('ids',$_SESSION) && !empty($session)) {
return true;
// the session exists
} else {
return false;
// the session does not exist
}
}
function variable_exists($post_id, $session) {
if (in_array($post_id, $session)) {
// we have the id in the array
return true;
} else {
// we don't have the id in the arary
return false;
}
}
function add_to_lightbox($post_id, $session) {
if (!session_exists($session) == true && variable_exists($post_id, $session) == false) {
// add the id to the array
array_push($session, $post_id);
var_dump($session);
} else {
// create a new array with our id in it
$session = [$post_id];
var_dump($session);
}
}
It's stuck in a state where it's always getting to add_to_lightbox()
and following the array_push($session, $post_id);
each time. I’m unsure whether this code I’ve written is possible because of the nested functions, and how I can refactor it to get the functionality working.