Problems with isset() and $_SESSION variables - php

I'm currently working on a project that requires session variables to store search information, which is pretty common place. Typically, I've used isset() to check if a session variable exists. However, there seems to be a problem that is bewildering...not sure what is going on. Any help is appreciated. The code...
<?php
# Check to make sure the session is started
if (session_id() != '') echo 'Session has started<br/>';
# Check every possible way I know to make sure variable is set
if (array_key_exists('adminsearchrange', $_SESSION) && isset($_SESSION['adminsearchrange'])
&& !empty($_SESSION['adminsearchrange']) && $_SESSION['adminsearchrange'] != NULL) {
echo 'Search range is set and is not empty<br/>';
echo $_SESSION['adminsearchrange'];
}
?>
The output...
Session has started
Search range is set and is not empty
Notice: Undefined index: adminsearchrange in /Users/.../events_items.php on line 1182
Based on the comments, I took the simplest approach...created a new file whose entire contents is listed below. Still get the same error (above), and oddly enough, it still references the the exact line and file (even though that file is not being included in any way)...and no, there isn't any .htaccess rewriting of any sort. The code (all in one file)...
<?php
session_start();
if (session_id() != '') echo 'Session has started<br/>';
if (array_key_exists('adminsearchrange', $_SESSION) && isset($_SESSION['adminsearchrange'])
&& !empty($_SESSION['adminsearchrange']) && $_SESSION['adminsearchrange'] != NULL) {
echo 'Search range is set and is not empty<br/>';
echo $_SESSION['adminsearchrange'];
}
?>

It appears the session was hosed (somehow). A simple session_destroy() solved the problem.

Related

Is the PHP Manual misguiding regarding the output of 'phpinfo()' function?

I'm using Windows 10 Home Single Language Edition which is a 64-bit Operating System on my machine.
I've installed the most latest version of XAMPP which has installed PHP 7.2.6 on my machine.
I come across the following sentence from the paragraph in PHP Manual
Make a call to the phpinfo() function and you will see a lot of useful
information about your system and setup such as available predefined
variables, loaded PHP modules, and configuration settings.
I tried executing the below script and saw the output in my web browser :
<?php phpinfo(); ?>
I checked the entire output carefully. In the output of phpinfo() I could only see the $_SERVER predefined variable along with it's possible indexes specific to set-up on my machine.
But what about other predefined variables in PHP viz. $GLOBALS, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV, $http_response_header, $argc, $argv?
According to what the text from PHP Manual is saying all the above mentioned predefined variables along with their respective values should be displayed in the output of the script <?php phpinfo(); ?> but it's not happening. Why so?
Is the text from PHP manual misguiding the users of PHP?
Or am I getting the wrong understanding of the text from PHP Manual?
Please explain me in detail.
As you can see in the PHP source code for phpinfo(), it will display the variables in question:
if (flag & PHP_INFO_VARIABLES) {
zval *data;
SECTION("PHP Variables");
php_info_print_table_start();
php_info_print_table_header(2, "Variable", "Value");
if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_SELF", sizeof("PHP_SELF")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
php_info_print_table_row(2, "PHP_SELF", Z_STRVAL_P(data));
}
if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_AUTH_TYPE", sizeof("PHP_AUTH_TYPE")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
php_info_print_table_row(2, "PHP_AUTH_TYPE", Z_STRVAL_P(data));
}
if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_AUTH_USER", sizeof("PHP_AUTH_USER")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
php_info_print_table_row(2, "PHP_AUTH_USER", Z_STRVAL_P(data));
}
if ((data = zend_hash_str_find(&EG(symbol_table), "PHP_AUTH_PW", sizeof("PHP_AUTH_PW")-1)) != NULL && Z_TYPE_P(data) == IS_STRING) {
php_info_print_table_row(2, "PHP_AUTH_PW", Z_STRVAL_P(data));
}
php_print_gpcse_array(ZEND_STRL("_REQUEST"));
php_print_gpcse_array(ZEND_STRL("_GET"));
php_print_gpcse_array(ZEND_STRL("_POST"));
php_print_gpcse_array(ZEND_STRL("_FILES"));
php_print_gpcse_array(ZEND_STRL("_COOKIE"));
php_print_gpcse_array(ZEND_STRL("_SERVER"));
php_print_gpcse_array(ZEND_STRL("_ENV"));
php_info_print_table_end();
}
However, as you can see, it uses php_print_gpcse_array to print each key/value pair in it when a) the superglobal exists (SAPI dependent) and b) it actually contains values.
TL;DR: no, the PHP manual is not misleading in that regard.

How to destroy a started session without warning?

I'm going mad !
function initialize() {
session_start(); //EDITED
if(blnSessionIsStarted() && !session_destroy()) // Destroy session on disk
return false;
...
if(!blnSessionIsStarted() && !session_start()) //EDITED
return false; //EDITED
} //EDITED
function blnSessionIsStarted()
{
//From: http://uk3.php.net/manual/en/function.session-status.php#113468
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() == '' ? FALSE : TRUE;
}
}
return FALSE;
}
In my site, this returns a
PHP WARNING (2): session_destroy(): Trying to destroy uninitialized session
Within blnSessionIsStarted(), session_id() contains a non-empty session string, hence the function returns true. I am using PHP 5.3.10. I want to get rid of this warning, but everywhere I read, the code used seems to be the best practice out there. Am I missing something?
EDIT
Following the advice from some users and looking up their feedback, I added some edited lines.
However, now it's returning another error (notice) 'PHP NOTICE (8): A session had already been started - ignoring session_start()'.
But, these changes are irrelevant: Why does blnSessionIsStarted() return true even though the session has not been started yet, and if so, how does one accurately detect that the session has been started, without enforcing the call to session_start() before? And why is there a notice thrown when session_start() is re-called, and how to detect that a session_start() cant be called, even though blnSessionIsStarted() says it is no longer started?
You need to call, session_start(); first. There is no session right now.

Constant, isset and empty evaluation

Does anyone know how isset and empty is interpreted by the translator, or how the translator treats undefined variables?
To expand on my question, I have the below code in my include file:
define('USER_AUTH', !empty($_SESSION['username']) && !empty($_SESSION['status'])); //user is verified
define('ACC_IS_PENDING', $_SESSION['status'] == '0');//checks to see if user status is pending which has a status of 0
USER_AUTH is used as a quick hand to check if user is authenticated. ACC_IS_PENDING is used as a quick hand for when the account status is pending. However, PHP gives me a notice to advise me that $_SESSION['status'] in my second line of code is undefined. I know that it is undefined, but I haven't used it yet! How dare you tell me what I already know. LoL
However, when I trick the code with the below:
define('USER_AUTH', !isempty($_SESSION['username']) && !isempty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Where isempty() is a custom made function that will always return FALSE. Then no notice!
Alternatively, if I use the below code:
define('USER_AUTH', notempty($_SESSION['username']) && notempty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Where notempty() always return TRUE, then again no notice.
Am I right in saying that the translator checks that the variable has been tested once, and that if the test resulted in true, then the translator sees this as the variable has been defined?
If this was the case, then what about isset and empty? They both seem to give me notices no matter if the evaluation is true or false.
define('USER_AUTH', isset($_SESSION['username']) && isset($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
and
define('USER_AUTH', empty($_SESSION['username']) && empty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Apologies for the long winded question. This seems trivial, but it would be nice to have a quick defined constant without having to get notices! Any help in explanation or a better solution for such trivial task would be appreciated, thanks!
PHP complains because the index 'status' is not defined in the array. You would need to write
!isset($_SESSION['status']) || empty($_SESSION['status']
When you "trick" the code as described, PHP will never try to access the non-existing array index, which is why you don't get any notice.
In the fourth code example (with isset), you are still accessing the non-existing array index in the second line of code, so I suspect that's why there's still a notice.
a) If you wants to use $_SESSION['status'], you have to check first that the variable is not empty ( see http://www.php.net/manual/fr/function.isset.php for more details) :
if (isset($_SESSION['status'])) {
// here the value exists and can be used
Do something...
} else {
// here the value does not exist and cannot be used
}
b) I believe that
empty($_SESSION['username']) && !empty($_SESSION['status'])
is not constant : it varies from one run to the other. You may want to use
$user_is_logged = empty($_SESSION['username']) && !empty($_SESSION['status']);
and use the variable $user_is_logged instead of a constant. See this section http://www.php.net/manual/fr/language.constants.php for a speek about constants.

Undefined index: When converting cookie value to variable

The problem
The following code produces this error from the line "print $readerStatus" -
Undefined index: readerStatus
Code
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} Else {
$readerStatus="Not Set";}
echo "The value of Cookie readerStatus is " . $_COOKIE['readerStatus'];
print $readerStatus;
?>
Background
The goal is simply that if a cookie is set I want to pass the value into a Javascript. My strategy is as follows:
Get the value from the cookie
Set a variable to the value of the cookie
Then use a php echo inside of the Javascript to transfer the value.
It works as expected but Eclipse is giving me the error and so I assume there is something wrong with the above code.
I'd appreciate any pointers on possible sources of the problem.
Thanks
Is this working?
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} else {
$readerStatus="Not Set";
}
echo ("The value of Cookie readerStatus is ".$readerStatus);
print ($readerStatus);
?>
This is a warning, not an error. However, you can skip the error by using array_key_exists. Generally, I'm not a fan of isset for this kind of checking.
if (array_key_exists('readerStatus', $_COOKIE))
{
$readerStatus=$_COOKIE['readerStatus'];
}
else
{
$readerStatus='Not Set';
}
echo 'The value of Cookie readerStatus is '. $readerStatus;
Some IDEs are less forgiving than the PHP parser itself. That being said, do you get any errors or notices when running the code? Variables in PHP are implicitly declared, so the undefined index message is simply a NOTICE (that can be ignored) regarding the accessing of an array element without it existing first.
If you check it exists prior to accessing it like this, you shouldn't have a problem.
$readerStatus = isset($_COOIKE['readerStatus']) ? $_COOIKE['readerStatus'] : '';

PHP: Notice: Undefined index where the session variable is defined

I am making a registration system with an e-mail verifier. Your typical "use this code to verify" type of thing.
I want a session variable to be stored, so that when people complete their account registration on the registration page and somehow navigate back to the page on accident, it reminds them that they need to activate their account before use.
What makes this problem so hard to diagnose is that I have used many other session variables in similar ways, but this one is not working at all. Here's my approach:
/* This is placed after the mail script and account creation within the same if
statement. Things get executed after it, so I know it's placed correctly. */
$_SESSION['registrationComplete'] = TRUE;
// I've tried integer 1 and 'Yes' as alternatives.
Now to check for the variable, I placed this at the top of the page.
echo $_SESSION['registrationComplete']; // To see if it's setting. This gives the
// undefined index notice.
if (isset($_SESSION['registrationComplete'])) {
// Alternatively, I have nested another if that simply tests if it's TRUE.
echo $_SESSION['registrationComplete']; // When echo'd here, it displays nothing.
echo '<p>Congratulations, Foo! Go to *link to Bar*.</p>';
}
Now, I used to have the page redirect to a new page, but I took that out to test it. When the page reloads from submit, my message in the if statement above appears and then I get an Notice: Undefined index: registrationComplete blah blah from the echoing of the session var!
Then if I ever go back to the page, it ignores the if statement all together.
I have tested for typos and everything, clearing session variables in case old ones from testing were interfering, but I am having no luck. A lot of Googling just shows people suppressing these errors, but that sounds insane! Not only that, but I am not getting the same persistence of session variables elsewhere on my site. Can someone point out if I'm doing something blatantly wrong? Help! Thanks!
FYI, I read several related questions and I am also a beginner, so I may not know how to utilize certain advice without explanation.
As requested, more code, heavily annotated to keep it brief
var_dump($_SESSION);
// It's here to analyze that index message. I guess it's not important.
echo $_SESSION['registrationComplete'];
if (isset($_SESSION['registrationComplete'])) {
// The golden ticket! This is what I want to appear so badly.
echo 'Congratulations, Foo! Go to *link to Bar*.';
}
// Explanation: I don't want logged in users registering.
// The else statement basically executes the main chunk of code.
if (isset($_SESSION['user_id'])) {
echo 'You are logged in as someone already.';
}
else {
if (isset($_POST['submitRegister'])) {
// Code: Database connection and parsing variables from the form.
if (!empty($email) && !empty($email2) && $email == $email2 && !empty($displayName) && !empty($password) && !empty($password2) && $password == $password2) {
// Code: Query to retrieve data for comparison.
if (mysqli_num_rows($registrationData) == 0) {
// Code: Generates the salt and verification code.
// Code: Password hashing and sending data to verify database.
// E-mail the verification code.
$_SESSION['registrationComplete'] = 'yes';
}
else {
// Some error handling is here.
$registerError = 'The e-mail address you entered is already in use.';
}
}
// the elseif, elseif, and else are more error handling.
elseif ($email != $email2) { $registerError = 'Your e-mails did not match'; }
elseif ($password != $password2) { $registerError = 'Passwords didn\'t match.'; }
else { $registerError = 'Filled out completely?'; }
// If the registration was submitted, but had errors, this will print the form again.
if (!isset($_SESSION['registrationComplete'])) { require_once REF_DIR . REF_REGISTERFORM; }
// IMPORTANT! it turns out my code did not work, I forgot I had the same statement elsewhere.
else { echo 'Congratulations, Foo! Go to *link to Bar*.'; }
}
// Creates form.
else { require_once REF_DIR . REF_REGISTERFORM; }
}
This came down to the basics of debugging/troubleshooting.
Understand as much as you can about the technique/library/function/whatever that you're trying to use.
Inspect the salient bits and make sure that they are what you expect or what they should be. (There's a slight difference between those two, depending on the situation.)
If that doesn't bring you towards a solution, step back and make sure you're understanding the situation. This may mean simplifying things so that you're only dealing with the issue at hand, i.e. create a separate, simpler test case which exposes the same problem. Or, it may simply mean that you stop coding and work through the flow of your code to make sure it is really doing what you think it is doing.
A typical issue with sessions not working is forgetting to use session_start() (near or at the top) of any page which uses sessions.
One of my favorite snippets of PHP code, for debugging:
print '<pre>';
var_dump($some_variable);
print '</pre>';
I try to use print for debugging and echo for regular output. It makes it easier to spot debugging code, once it's goes beyond a few trivial bits of output.
Meanwhile, var_dump will print a bit more info about the variable, like it's type and size. It's important to wrap it in <pre></pre> so that it's easier to read the output.
Try
if (!empty($_SESSION['registrationComplete'])) {
If you get the warning after the message is printed, this cannot come from the variable echoing because according to your code it would be thrown before printing that message. Are you sure you don't use $_SESSION['registrationComplete'] beyond the if statement? Try to add exit or die() before the closing bracket of the if and see if the notice disappears.

Categories