Link to home
Start Free TrialLog in
Avatar of Atul_Sachdeva
Atul_Sachdeva

asked on

Session_register Warning in PHP

I am using this PHP code as a part of a bigger project. This is used to subscribe the user. After the user is subscribed, I am tying to set up a session using a session variable using the following code

session_register("userlogged");

$_SESSION["userlogged"]=$user;

header("Location:promosignupSuccessful.php5?status=true");

But I am getting the following warning

Warning: session_register() [function.session-register]: Cannot send session cookie - headers already sent by (output started at /home/tune/public_html/promo.php5:1) in /home/tune/public_html/promo.php5 on line 208

Warning: session_register() [function.session-register]: Cannot send session cache limiter - headers already sent (output started at /home/tune/public_html/promo.php5:1) in /home/tune/public_html/promo.php5 on line 208

Warning: Cannot modify header information - headers already sent by (output started at /home/tune/public_html/promo.php5:1) in /home/tune/public_html/promo.php5 on line 212

The PHP code is attached

Can anybody help?
<?php
 require_once('IConstants.php5');
 require_once( IConstants::$ServerURL."DataStoreMgr/UserDataStore.php5");
 require_once( IConstants::$ServerURL."DataStoreMgr/MobileSeriesDataStore.php5");
 require_once( IConstants::$ServerURL."FormValidator/validator.php5");
 require_once( IConstants::$ServerURL."Services/SecurityUtil.php5");
 require_once( IConstants::$ServerURL."Services/MailService.php5");
 require_once( IConstants::$ServerURL."Services/SMSService.php5");
 require_once( IConstants::$ServerURL."PromoData.php5");
 require_once( IConstants::$ServerURL."BusinessObjects/SearchParams.php5");
 require_once( IConstants::$ServerURL."DataStoreMgr/SearchParamsDataStore.php5");
 


$msg="";
$userNameMsg = "";
$emailIdMsg="";
$mobileMsg="";
$passwordMsg="";
$confirmPasswordMsg="";
$countryMsg="";

		$userDataStore = UserDataStore::getInstance();
        $userName ="";
        $emailId= "";
        $mobile = "";
		$password = "";
        $confirmPassword ="";
        $country = "";
        $reply="";
        $Promo= "";



 $promoData = new PromoData();
 $replyPromo = $promoData->currentPromo("CHANNEL");
 if ($replyPromo !=null)
 {
 	$Promo = "Channel ";
 	$Promo = $Promo.$replyPromo;
 	$promoType = "Channel";
 }	
 else 
 {
 	$replyPromo = $promoData->currentPromo("VIDEO");
 	if ($replyPromo !=null)
 	{
 		$Promo = "Video ";
 		$Promo = $Promo.$replyPromo;
 		$promoType = "Video";
 	}
 	else
 	{
 		$Promo = "Sign up";	
 		$promoType = "NoPromo";
 	}
 }

if($_POST["submit"]<>""){

        
        $userName = $_POST["userName"];
        $emailId= $_POST["emailId"];
        $password = $_POST["password"];
        $confirmPassword = $_POST['confirmPassword'];
        $mobile = $_POST['mobileNumber'];
        $country = $_POST["country"];
        $isTermsRead =$_POST["isTermsRead"];

        $user = new User();

         //----------------Validation Code-------------------

		 function Formvalidator($objName,$objVal,$lenght,$isNullAllow){
             $valMsg=validator::validateform($objName,$objVal,$lenght,$isNullAllow);
             if ($valMsg<>null){
              user::setFlag(false);
              return $valMsg;
             }else{
                 if(user::getFlag() != false){
                    user::setFlag(true);
                 }

             }
             return null;
         }
            $userNameMsg = Formvalidator("User Name",$userName,56,false);
            $passwordMsg = Formvalidator("Password",$password,20,false);
            $confirmPasswordMsg = Formvalidator("Confirm Password",$confirmPassword,20,false);
            $countryMsg = Formvalidator("Country",$country,56,true);
            $emailIdMsg = Formvalidator("Emailid",$emailId,256,false);
            if($isTermsRead != "on"){
				$termsMsg = "Accept Terms and Conditons before signup";
				user::setFlag(false);
		 	}
            if(strlen($password)<7){
                $passwordMsg = "Password can not be less than 7 characters";
                user::setFlag(false);
            }

        if($password<>null){
             if ($password<>$confirmPassword) {
                $confirmPasswordMsg="Confirm password does not match with password";
                user::setFlag(false);
           }
        }

        $userFound = $userDataStore->getUserByUserName($userName);
        if($userFound != null){
          $userNameMsg = "User already registered, enter some other username.";
          user::setFlag(false);
        }

        if( $emailId!= "" || $emailId != NULL){
          $ev = validator::validateEmailAddress($emailId);
          if($ev == false){
              user::setFlag(false);
              $emailIdMsg = "Enter a valid email id";
          }
        }

        if($mobile != "" || $mobile != NULL){
            if(strlen($mobile) != 10){
                $mobileMsg  =  "Invalid Mobile number";
                user::setFlag(false);
            }
            if($mobileMsg == ""){
                $MSDS = MobileSeriesDataStore::getInstance();
                $isValidMobileNumber = $MSDS->isValidPrefix($mobile);

                if($isValidMobileNumber == false){
                    $mobileMsg = "Invalid Mobile number";
                    user::setFlag(false);
                }
            }

        }
            $earlierUser = $userDataStore->getUserByEmail($emailId);
                if($earlierUser != null){
                    user::setFlag(false);
                     $emailIdMsg = "Entered Email id already exists";
                }
            if(user::getFlag() == true){
                $user = new User(0,$userName,$emailId,$password,$mobile,$country);
                $user->setUserSignupDate(date("m.d.y"));

                if($emailId != null){
                    $securityUtil = new SecurityUtil();
                    $encodedEmailId = $securityUtil->Encode($emailId);
                    $user->setEmailVerificationCode($encodedEmailId);
                }
                if($mobile != null){
                    $securityUtil = new SecurityUtil();
                    $encodedMobileNumber = $securityUtil->getEncodedMobileVerificationId($mobile);
                    //left 5 characters of encoded mobile number is the verficiation id
                    $user->setMobileVerificationCode($encodedMobileNumber);
                }

                $errmsg = $userDataStore->Save($user);
                if($errmsg == 1){
                    if($user->getUserEmail()!= null){
                        $mailService = new MailService();
                        $mailService->sendRegistrationEmail($user);
                    }
                    if($user->getUserMobile()!= null){
                        $smsService = new SMSService();
                        $reply = $smsService->sendVerificationSMS($user);
                    }
                        
                        //Commented This
                        
                        /*
                        $user = $userDataStore->getUserByUserName($user->getUserName());
                        session_register('userlogged');
                        $_SESSION['userlogged']=$user;
                        header("Location:signupSuccessful.php5?status=true");*/
                        
                        // Till Here
                        
                        //Set the search parameter as well
                        
			if($promoType != "NoPromo")
			{	
				$userDataStore = UserDataStore::getInstance();
				$user = $userDataStore->validateUserLogin($userName,$password);
				$searchParams =  new SearchParams();
				$searchParams->setUserSeq($user->getUserSeq());
				//echo "User seq is " . $user->getUserSeq();				
				$searchParams->setSearchQ($replyPromo);
				$SDS = SearchParamsDataStore::getInstance();
				//echo "var is " . $promoType;
				//echo "newvar is " . $replyPromo;
				if(strtoupper($promoType) == "VIDEO")
				{
					$searchParams->setIsVideo(1);
					//echo " I am here Video";
				}
				else
				{                        
					$searchParams->setIsChannel(1);
					//echo "var is " . $promoType;
					//echo " I am here Channel";
				}                        
				$SDS->Save($searchParams);
				
				session_register("userlogged");

				$_SESSION["userlogged"]=$user;

				header("Location:promosignupSuccessful.php5?status=true");
				
				
				
				//echo "You are now following the saved program " . $replyPromo ;
			}			
                        
                }else{
                    //$words = explode(" ", $errmsg);
//                    if(in_array($emailId,$words)){
//                        if(in_array("Duplicate",$words)){
//                           $emailIdMsg = "Entered Email id already exists";
//                        }
//                    }

                }
            }


}?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
<link type="text/css" rel="stylesheet" href="common/styles.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript" src="jquery.datePicker.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="datePicker.css" />
<script src="js/AjaxCode.js"></script>

</head>

<body>

<?php include("header.php5"); ?>

<table width="1000" border="0" align="center" cellpadding="3" cellspacing="3" style="padding:20px 120px 60px 120px; background-color:#FFFFFF; font-weight: bold; font-family: 'Comic Sans MS', cursive; font-style: italic;">
  <form name="frm1" method="post" action="promo.php5">
  <tbody>
 <!-- <tr>
  <td colspan="2" class="message" style="color: red;" align="center"><?php echo($msg);?> </td>
  </tr> -->
  </tbody>
  <tr>
    <td bgcolor="#FFFFFF" colspan="2" class="Description"><?php echo $Promo ?></td>
  </tr>
  <tr>
  <td height="92" rowspan="4" bgcolor="#FFFFFF">
  <div class="formTD"> <label class="formCaption">Username
    : <br />
  <input name="userName" id="userName" size="40" type="text" value=<?php echo $userName ;?>   >*
  <br />
  </label> <label class="formDetail">Enter a
    unique username. </label> <label id="redSmallFont"><? echo $userNameMsg ?></label>
  </div>
  </td>
  <td rowspan="4" bgcolor="#FFFFFF">
    <div class="formTD"> <label class="formCaption">Password:
      <br />
      <input name="password" size="40" type="password" />
      * </label> <label class="formDetail"> Always use
        alphanumeric passwords. </label> <label id="redSmallFont"> <? echo $passwordMsg?></label>
      </div>
  </td>
  <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
  <tr>
  <td rowspan="5" bgcolor="#FFFFFF">
  <div class="formTD"> <label class="formCaption">Confirm
    Password: <br />
  <input name="confirmPassword" size="40" type="password" /> * </label> <label class="formDetail">Confirm password.</label> <label id="redSmallFont"> <? echo $confirmPasswordMsg?></label> </div>
  </td>
  <td width="316" rowspan="5" bgcolor="#FFFFFF">
    <div class="formTD"> <label class="formCaption">Email
      Id: <br />
      <input name="emailId" size="40" type="text" value=<?php echo $emailId ;?>  > *</label>
      <label class="formDetail">Enter a valid email id.
        You will receive a verification email.<br />
        You will get video alerts on this email id.</label> <label id="redSmallFont">  <? echo $emailIdMsg?></label> </div>
  </td>
  <td width="205" bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr bgcolor="#FFFFFF">
  <td width="478">
  <div class="formTD"> <label class="formCaption">Mobile
    Number: <br />
  <input name="mobileNumber" size="40" type="text" value=<?php echo $mobile;?>  > </label>
  <label class="formDetail"> Enter your working mobile
    number.<br />
    You will get video alerts on your mobile phone.</label> <label id="redSmallFont"> <? echo $mobileMsg?></label> </div>
  </td>
  </tr>
  <tr>
  <td align="left" bgcolor="#FFFFFF">
  <div style="margin-left: 10px;"> <label class="formCaption"> <input name="isTermsRead" id="isTermsRead" size="40" type="checkbox" />
    I have read <a href="terms.php5" class="smallLinkGray" target="_blank">Terms and Conditions</a> before
    signup. </label><br />
  <label id="redSmallFont"> <? echo $termsMsg ?></label> </div>
  </td>
  <td align="left" bgcolor="#FFFFFF">&nbsp;</td>
  <td align="left" bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td align="right" bgcolor="#FFFFFF"> <input name="submit" value="Submit" class="button" type="submit" />
      </td>
    <td align="left" bgcolor="#FFFFFF"> <input name="" reset="" value="Reset" class="button" type="reset" /> </td>
    <td align="left" bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr bgcolor="#FFFFFF"></tbody>
  </form>
</table>

<?php include("footer.php5"); ?>

</body></html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of dsmile
dsmile
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Add this line of PHP code before you call any functions (right after <?php)

ob_start();
Avatar of Atul_Sachdeva
Atul_Sachdeva

ASKER

Thanks, it worked. Can you please tell me what was the exact issue? How did it get resolved?
In order to use and declare session variables you must start the session. It's a one liner and for good programming purposes should be the very first line of your php page. The line simply is: session_start(); Try putting this at the beginning and see if that helps.

cheers
Anything relates to header (session, cookies,... and header() commands) must be called prior to any output to the screen.
This means if there're any output to the screen (even white spaces by mistaken) before calling header, they will cause error of header command after that.
@dsmile The code you sent worked perfectly fine

Can you please explain what changes you did in the code? How do I can do that and make sure I don't encounter such error again
The effect of ob_start() is twofold - first, it will make you web pages load much faster.  And second, it will collect all the browser output into a buffer, so you can issue header commands without fear of running afoul of the HTTP rules that all headers must come before and be complete before any browser output.

That said, you might want to take a look at the large red warning box on this function:
http://us2.php.net/manual/en/function.session-register.php

Best of luck with your project, ~Ray
@Atul_Sachdeva: as I said in post #34212824: "I trimmed white spaces in your file".

Your original file may have some unexpected white spaces before <?php on the first line that caused the error.
All you need to do is delete it (most of the IDE provides a function named trim trailing spaces)

I'll explain this error in detail, so that you can fix it yourself next time

Warning: session_register() [function.session-register]: Cannot send session cookie - headers already sent by (output started at /home/tune/public_html/promo.php5:1) in /home/tune/public_html/promo.php5 on line 208

This error tells us two things:
1. error occurs on line 208 of promo.php5 --> doesn't help much 'cause in this type of error, it's always a header related statement.
2. the cause starts on line 1 of promo.php5 --> this is where we get to in order to fix the error

To fix: just look into line 1 of promo.php5, and delete any unexpected white spaces (spaces, tabs, ..) you can find there.
Usually, unexpected white spaces come before <?php cause this error.

To prevent this error from occurring again, use an IDE that supports 'trim trailing spaces' (eg: Edit Plus)