Prasoon Saurav
Prasoon Saurav

Reputation: 92864

setting default value of superglobal

I have been working on a Timesheet Management website. I have my home page as index.php

//index.php (only relevant portion shown)
<?php
      session_start();

    if($_SESSION['logged']=='set')
    {

       $x=$_SESSION['username'];

              echo '<div align="right">';
              echo 'Welcome ' .$x.'<br/>';
              echo'<a href="logout.php" class="links">&nbsp;<b><u>Logout</u></b></a>' ;   

    }   

    else if($_SESSION['logged']='unset')
    {
             echo'<form id="searchform" method="post" action="processing.php">
                  <div>
                  <div align="right">
                  Username&nbsp;<input type="text" name="username" id="s" size="15" value="" />
                  &nbsp;Password&nbsp;<input type="password" name="pass" id="s" size="15" value="" />
                  <input type="submit" name="submit" value="submit" />
                  </div>
                  <br />
                  </div>
                  </form> ';

     }
?>

The problem I am facing is that during the first run of this script I get an error Notice: Undefined index: logged in C:\wamp\www\ps\index.php but after refreshing the page the error vanishes.

How can I correct this problem? logged is a variable which helps determine whether the user is logged in or not. When the user is logged in $_SESSION['logged'] is set, otherwise unset. I want the default value of $_SESSION['logged'] to be unset prior to the execution of the script. How can I solve this problem?

Upvotes: 0

Views: 301

Answers (2)

Jan K.
Jan K.

Reputation: 1608

you can also prevent a function from throwing an error if you use the '@' symbol, e.g. @function_call();.

do you really want to do "if($_SESSION['logged']='unset')" ? if you want to make an assignment, consider taking out the "if" to make your code more legible. otherwise, you probably wanted to use the equality operator. :-)

Upvotes: 2

Gumbo
Gumbo

Reputation: 655319

When the session is initially started, $_SESSION is an empty array and $_SESSION['logged'] does not exist. And read access to uninitialized variables or array indexes throw a notice (given that the error reporting level covers notices):

echo $undefinedVariable;

$emptyArray = array();
echo $emptyArray['undefined index'];

To tackle this you should test if the variable or array index you want to read actually exists. For variables there is isset and for array indices you can either use isset too or array_key_exists.

Upvotes: 3

Related Questions