Hey guys, I have an issue that I am not sure can be fixed, but I realy want my code to do this. It is the most elegant way and most OOP way I can think of. If you have any other suggestions feel free to chime in.

In my admin i have a checklogin class that checks to see if the user is logged in via a session and if the user isnt logged in it sends them to the login page using a "header("Location: ")" type deal. This works fine.

But I also have a successError class that does the same thing. If the page completed succesfully it uses "header("Location: ".$successPage."?msg=".$msg);" if the page has an error it uses "header("Location: ".$errorPage."?msg=".$msg."&email=".$email);"

The problem is I get a "headers already sent" message when this class tries to do it's job.

Here is a sample page in my admin, thanks for looking at it. I am removing most of the HTML because it is too long..The HTML isnt important here anway.

<?php

require_once("../includes/success_error.class.php");
require_once("../includes/check_session.class.php");
require_once("../includes/db_vars.inc.php");
require_once("../includes/mysql_con_tran.class.php");
$s = new session();
$s->checkSession("USER_ID","login.php");
$path = "http://11111111/admin/";
$themeBGColor="#05639B";
$themeForeColor="#FFFFFF";
$email = "email@sdf.com";
?>

 <!-- InstanceBeginEditable name="EditRegion3" -->
        <table cellpadding="4">
          <tr>
            <td><?php
			$se = new successError();
			$db = new mySQLConTran();

$btnImageName=$_FILES['btnImage']['name'];
$btnImageTmpName=$_FILES['btnImage']['tmp_name'];
$btnImageType=$_FILES['btnImage']['type'];
$imageName = str_replace (" ", "_", $btnImageName);
$imageName = str_replace ("-", "_", $imageName);
$imageName = str_replace ('"', "_", $imageName);
$imageName = str_replace ("'", "_", $imageName);
$imageName = str_replace (">", "_", $imageName);
$imageName = str_replace ("<", "_", $imageName);

 if (!empty($btnImageName)){
	  if ((!$btnImageType == "image/pjpeg" AND !$btnImageType == "image/jpeg") OR !$btnImageType == "image/gif"){
	   $error .= "Image must be in either .jpg or .gif format.<br>";
	   }
    // Check To Make Sure Image Is Of Right Dimensions //
	  $imageSize = getimagesize($btnImageTmpName);
      $imageWidth = $imageSize[0];
      $imageHeight = $imageSize[1];
	 //If ($ImageWidth > 500)$Error .= "<img src=\"../images/bullet.gif\" border=0>Image is not the correct size, it must be less than 500 pixels wide.<br>";
     }
if ($error != ""){
$se->errorMessage($path."mainfiles/error.php",$error,$email);
	 }else{
  $fullPath = "/home/httpd/vhosts/hopecommunitychurch.net/httpdocs/admin/emailer/insertimages/";
   if (!empty($btnImageTmpName)){
  copy($btnImageTmpName,$fullPath.$btnImageName);

  if(!copy) $se->errorMessage($path."mainfiles/error.php","Unable to copy image.",$email);
  unlink ($btnImageTmpName);
  }
  }

//Update DB
if(!$btnImageName) $btnImageName = "top.jpg";
$db->dbOpen($dbName,$dbHost,$dbUser,$dbPass);
$sql = "INSERT INTO tblEmailImages (Image) VALUES ('$btnImageName')";
$try = $db->dbCommand($sql);

  if (!$try){
   $se->errorMessage($path."mainfiles/error.php","SQL insert error.",$email);
  }else{
 $se->successMessage($path."mainfiles/success.php","Image succesfully added.");
  }
?></td>
          </tr></table> <!-- InstanceEndEditable --> 
      </td>
      <td width=3 bgcolor="#000000"> <img src="<?php echo $path; ?>images/spacer.gif" width=3></td>
    </tr>
  </tbody>
</table>

<table width="754" border="0" bgcolor="#000000" align="center" cellpadding="3" cellspacing="2">
  <tr>
    <td height="8"><img src="<?php echo $path; ?>images/spacer.gif" width=2></td>
  </tr>
</table>
</td>
    <td bgcolor="#000000" width=3><img src="<?php echo $path; ?>images/spacer.gif" width=2></td>
  </tr>
</table>

</body>
<!-- InstanceEnd --></html>

Here are the two classes

class successError{


function errorMessage($errorPage, $msg, $email){
		header("Location: ".$errorPage."?msg=".$msg."&email=".$email);
}//end ErrorMessage

function successMessage($successPage, $msg) {
	header("Location: ".$successPage."?msg=".$msg);
}//end SuccessMessage

}//end class SuccessError



----------------------------------------------------------------------




class session{
	function checkSession($sessionName, $errorRedirect){
		session_start();
		if (!isset($_SESSION[$sessionName])){
			header("Location: ".$errorRedirect);
		}else{
			header("Cache-Control: no-cache, must re-validate");
			header("Pragma: no-cache");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		}//end if
	}//end function checkSession
}//end class Session
    <!-- InstanceBeginEditable name="EditRegion3" -->
            <table cellpadding="4">
              <tr>
                <td><?php
                $se = new successError(); 
    

    befor header(); can't have any output
    but in you code


    <!-- InstanceBeginEditable name="EditRegion3" -->
    <table cellpadding="4">
    <tr>
    <td>

      As artlover pointed out, you cannot output ANY data before sending extra HTTP headers. Your current cod escapes out of PHP and outputs some HTML before it even has a chance to process your error class. Now, to fix this, you can do one of two things:

      1. Use output controlling methods (man page: [man]outcontrol[/man]) such as [man]ob_start/man to buffer all output before sending it. Instead of escaping out of PHP to echo HTML, just enclose it in an echo() statement. Note this can and will result in more memory usage since all of the data has to be buffered to memory before it is sent along to the httpd.

      2. Instead of outputting data, store/append it to a variable, such as $output. Continue on with your script, handling errors if necessary, appending more output to the end of your variable, etc. At the end, simply echo out $output if no errors have occured up to this point.

      3. An even better idea, as mentioned by Weedpacket below. :o Do your error-checking/-validating first and then start building your output.

      It would take a minor bit of rewriting, but I personally choose the 2nd route when dealing with this type of situation.

        Thanks for the input guys. I'll give that a shot. 🙂

          1. Do some planning and work out what the page is supposed to do before acting on it. If you're going to be redirecting the user to another page there's no point even storing output in a variable that you're just going to throw away (and there's certainly no point in outputting it).
            Write a Reply...