Is it better to do something like this at the top a PHP page:
if (isset($_SESSION['firstName'])) {
$firstName = $_SESSION['firstName'];
}
if (isset($_SESSION['sponsorID'])) {
$sponsorID = $_SESSION['sponsorID'];
}
And then be able to successfully evaluate the values like this:
if ($firstName && $sponsorNumber > 0) {
//Execute code
}
I am asking this because I’m trying to clean up my PHP across my website, paying attention to the E-Notices that Apache is showing me in the error log. One of them was “Undefined Index”, so I solved it by using isset in my code. However, once I started doing this, my IF statements were failing. Here is an example:
if (isset($_SESSION['firstName']) && isset($_SESSION['sponsorNumber']) > 0) {
//Execute code
}
What the code currently does is check if firstName key exists and if the RETURN value of isset against $_SESSION[‘sponsorNumber’] is 0. Which actually means that when sponsorNumber exists it can be anything because the value returned by isset will be true (bool) which will casted to 1.
In general though when dealing with arrays you should always check the existence of an array key. Furthermore, when dealing with user controlled input of input that can be changed by the end user such as; cookie or form data validation is necessary.
$_SESSION is not user controlled. There’s no reason to copy $_SESSION variables to local variables - it’s busy-box coding and only creates an additional failure point in the code, particularly during refactoring.
There is a possibility of users tampering with $_SESSION data - so you should consider sanitiising it and moving the sanitised result to a local field if you are concerned about the possibility of tampering.
If you are not concerned about tampering then you should definitely NOT copy it as that could compromise the security of your entire application as you will not know which fields are sanitised and which are not.