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.
Related
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.
I am trying to encapsulate isset() and empty() in a function.
It worked fine on my home development sever (apache 2.4.3, PHP 5.2.17 under WinXP). When I ported it to my university Linux machine running Fedora, I got a notice about undefined index.
I checked my php.ini on my home computer, and error reporting is set to all. I put error_reporting(E_ALL); in my PHP script to try duplicate the error. It didn't happen.
Question 1: Why am I not getting the notice on my home development computer?
Here is my function:
<?php
function there($s) {
if (! isset($s)) {
return false;
}
if (empty($s)) {
return false;
}
return true;
}
?>
Here I test if a session variable exists:
if (! there($_SESSION['u'])) {
$_SESSION['u'] = new User();
}
I switched my function so that I test empty() before I test isset() thinking this will avoid getting the notice. I haven't had a chance yet to test this at school.
Question 2: Does empty() in general avoid giving a notice if the variable is undefined, or not set?
Question 3: Can I use my there() function to do this, or will I get the notice just by passing the undefined or unset parameter?
isset and empty are not functions, they are language constructs. As such, they can get away with such things as reading the literal variable name instead of trying to access the value. Any function you define can't do that.
With that in mind, there is no need to test for both. empty is a superset of isset, so you only really need to check for empty.
Your function is almost equivalent to !empty:
if (empty($_SESSION['u'])) {
$_SESSION['u'] = new User();
}
The only difference is: your wrapper function will complain if it's passed a variable that doesn't exist - whereas, as a language construct empty will not (and neither will isset).
Your sub-questions
Why am I not getting the notice on my home development computer?
Probably because you've got error reporting turned off.
Does empty() in general avoid giving a notice if the variable is undefined, or not set?
Yes.
Can I use my there() function to do this, or will I get the notice just by passing the undefined or unset parameter?
You will get notices about undefined variables.
As a way of proving #Kolink 's fine reply really, something which I had not realised ...
echo '<form action="" method=POST>
<input type=text value="" name="string" />
<input type=text value=0 name="int" />
<input type=submit />
</form>';
if( empty($_POST['string'] ) ){
var_dump( $_POST['string']) ;
}
if( empty($_POST['int'] ) ){
var_dump( $_POST['int']) ;
}
if( empty($_POST['something'] ) ){
echo 'something was not set, but you cannot var_dump it without a warning';
}
I realize this is an old thread, and it already has an accepted answer. So, I will not answer the questions again here. But for completeness sake and in the hope that it may help others I am sharing something I use.
Take a look at the following code:
<?php
echo var_dump($_SESSION['something']);
This will give you:
PHP Notice: Undefined variable: _SESSION in - on line 2
NULL
But if you do this:
<?php
echo var_dump(mycheck($_SESSION['something']));
function mycheck( &$var ){ // Note the & so we are passing by reference
return $var;
}
You will get:
NULL
This is because internally the $var variable will get created the instant the function is called. But since the $_SESSION['something'] does not exist, the $var is getting set to null which is then returned. Voila, notice gone. But be aware that the variable $_SESSION['something'] has now been created internally, even though isset($_SESSION['something']) will still return false because isset determines 'if a variable is set and is not NULL'.
PHP manual for isset: http://php.net/manual/en/function.isset.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.
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.
Can I set variables inside if-construct? In general, where is it allowed to set variables?
function set_login_session ( $passhash )
{
$_SESSION['login']['logged_in'] = 1;
if ( ERROR ) return false;
}
// Does it set the Session variable?
if ( set_login_session ( $passhash ) === false)
return false;
Short answer
Yes
Long answer
If this script has called start_session() earlier (or the session.auto_start configuration flag is set) then session variable can be set anywhere by using superglobal $_SESSION array.
Yes you can and it's allowed. But the thing is that what if the IF does not run and you incorrectly handle that situation.
So usually I initialize my big vars in the widest scope of the function and temporary vars is ok to be set inside somethings.
You should be aware though in your case. That you are initializing a global variable.
You haven't specified what the ERROR variable is. If it being true indicates an error, set_login_session can be essentially reduced to
$_SESSION['login']['logged_in'] = 1;
return !ERROR;
and the outer code to
return set_login_session( $passhash );
There's no need to do such explicit bool value comparisons.
And yes, it's perfectly valid to set variables in functions, but make sure the variable is set always, no matter of the code path taken, so there are no uninitialized/unexistant variables used in your code. Otherwise you're asking for trouble or, at least, big fat warnings in script output.
The $_SESSION superglobal should be present if there's a session started. If there was no ['login']['logged_in'] in it, that's fine.