Hello, I am pretty new to php
I have to restructure all my code to avoid the famous warning error
"Warning: Cannot modify header information - headers already sent by (output started at...)"
I get this at least 4 times in my code due to cookies and session start.
The .htaccess solution, with PHP_FLAG output_buffering on doesn't work on my server. So I am forced to handle my long code.
I looked a bit around and I have been given 4 guidelines:
1. put your DB queries on top of the page
2. have all (self-generated) functions return data only
3. build you HTML code inside a variable
4. print that variable at the end of the page
However, I am unable to follow these instructions even if I tried for a while now! here is the code:

<?php
include('../../../mysqlCon.php');
?>

<!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 http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
<link rel="stylesheet" type="text/css" href="css-accueil.css" />
<TITLE>Accueil</TITLE>
</HEAD>

<body onload="UpdateTimer();">
########SOME HTML CODE including menus#######

####until where header seems to be sent#####
#this function uses fopen and  fwrite#

<form method="post" action="biblio/bibli-storage.php">
<fieldset style="border:none">
<textarea name="user" style="width:210px; height:17px; overflow:hidden; margin-left:6px">pseudo</textarea><br />
<textarea name="lien" style="width:210px; height:50px; overflow:hidden; margin-left:6px">votre r&eacute;f&eacute;rence bibliographique</textarea>
<input style="float:right" type="submit" value="cr&eacute;er"  />
</fieldset>
</form>	
									
######AGAIN SOME HTML code:##########

#####FUNCTION FOR A LOGIN########
<?php	

error_reporting(1); // suppress warning messages

// Checking if the cookie exists
if(isset($_COOKIE['IDbruker'])) { 
	print'<p> Vous &ecirc;tes connect&eacute;(e)</p>';
 //if there is, it logs you in 
$username = $_COOKIE['IDbruker'];
$pass = $_COOKIE['Keybruker'];
$sjekker = mysql_query("SELECT * FROM usr WHERE name = '$username'")or die(mysql_error());
}


//if the login form is submitted
if ( isset($_POST['submit']) ) { // if form has been submitted

	// Checks if all fields are filled in
	if(!$_POST['brukernavn'] || !$_POST['pass']) {
		
		print'

		<form action="" method="post">
			<input type="text" name="brukernavn" value="pseudo" maxlength="20"><br><br />
			<input type="password" name="pass" value="mot de passe" maxlength="20"><INPUT type="submit" value="se connecter" name="submit" ALT="Submit Form" >		
		</form>
	';
	} else {
	
	
		// Checking against db
		$sjekk = mysql_query("SELECT * FROM survey WHERE username = '".$_POST['brukernavn']."'")or die(mysql_error());
		
		// Runs through the array and gives error if user doesnt exist
		$sjekk2 = mysql_num_rows($sjekk);
		if ($sjekk2 == 0) {
			
			print'

		<form action="" method="post">
			<input type="text" name="brukernavn" value="pseudo" maxlength="20"><br><br />
			<input type="password" name="pass" value="mot de passe" maxlength="20"><INPUT type="submit" value="se connecter" name="submit" ALT="Submit Form" >		
		</form>
	';
			
		}
		
		while($info = mysql_fetch_array( $sjekk )) {
			$_POST['pass'] = stripslashes($_POST['pass']);
			$info['password'] = stripslashes($info['password']);
			$_POST['pass'] = md5($_POST['pass']);
			
		
		
			// Checking the password
			if ($_POST['pass'] != $info['password']) {
				
				print'

		<form action="" method="post">
			<input type="text" name="brukernavn" value="pseudo" maxlength="20"><br><br />
			<input type="password" name="pass" value="mot de passe" maxlength="20"><INPUT type="submit" value="se connecter" name="submit" ALT="Submit Form" >		
		</form>
	';
				
				
			} else {
		
				// If all is ok, a cookie is made 
				$_POST['brukernavn'] = stripslashes($_POST['brukernavn']);
				$enTimeCookie = time() + 3600;
				setcookie('IDbruker', $_POST['brukernavn'], $enTimeCookie);
				setcookie('Keybruker', $_POST['pass'], $enTimeCookie);
				
				print'<p> Bienvenue!</p>	';
				
				
			}
		}
	}
} else { // if not logged in....
print'

		<form action="" method="post">
			<input type="text" name="brukernavn" value="pseudo" maxlength="20"><br><br />
			<input type="password" name="pass" value="mot de passe" maxlength="20"><INPUT type="submit" value="se connecter" name="submit" ALT="Submit Form" >		
		</form>
	';
}
?>
</div>
</div>

######CODE FOR INCLUDING GADGET GOOGLE CALENDAR#####


######CODE FOR A MICRO CHAT###############
<div class="chatbox">
<?php
session_start();

function createForm(){
?>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <table align="center">
          <tr><td colspan="2">Entrez un pseudo pour &eacute;crire!</td></tr>
          <tr><td>Votre nom: </td>
          <td><input class="text" type="text" name="name" /></td></tr>
          <tr><td colspan="2" align="center">
             <input class="text" type="submit" name="submitBtn" value="chatter" />
          </td></tr>
        </table>
      </form>
<?php
}

if (isset($_GET['u'])){
   unset($_SESSION['nickname']);
}

// Process login info
if (isset($_POST['submitBtn'])){
      $name    = isset($_POST['name']) ? $_POST['name'] : "Unnamed";
      $_SESSION['nickname'] = $name;
}

$nickname = isset($_SESSION['nickname']) ? $_SESSION['nickname'] : "Hidden";   
?>


    <script language="javascript" type="text/javascript">
    <!--
      var httpObject = null;
      var link = "";
      var timerID = 0;
      var nickName = "<?php echo $nickname; ?>";

      // Get the HTTP Object
      function getHTTPObject(){
         if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
         else if (window.XMLHttpRequest) return new XMLHttpRequest();
         else {
            alert("Your browser does not support AJAX.");
            return null;
         }
      }   

      // Change the value of the outputText field
      function setOutput(){
         if(httpObject.readyState == 4){
            var response = httpObject.responseText;
            var objDiv = document.getElementById("result");
            objDiv.innerHTML += response;
            objDiv.scrollTop = objDiv.scrollHeight;
            var inpObj = document.getElementById("msg");
            inpObj.value = "";
            inpObj.focus();
         }
      }

      // Change the value of the outputText field
      function setAll(){
         if(httpObject.readyState == 4){
            var response = httpObject.responseText;
            var objDiv = document.getElementById("result");
            objDiv.innerHTML = response;
            objDiv.scrollTop = objDiv.scrollHeight;
         }
      }

      // Implement business logic    
      function doWork(){    
         httpObject = getHTTPObject();
         if (httpObject != null) {
            link = "message.php?nick="+nickName+"&msg="+document.getElementById('msg').value;
            httpObject.open("GET", link , true);
            httpObject.onreadystatechange = setOutput;
            httpObject.send(null);
         }
      }

      // Implement business logic    
      function doReload(){    
         httpObject = getHTTPObject();
         var randomnumber=Math.floor(Math.random()*10000);
         if (httpObject != null) {
            link = "message.php?all=1&rnd="+randomnumber;
            httpObject.open("GET", link , true);
            httpObject.onreadystatechange = setAll;
            httpObject.send(null);
         }
      }

      function UpdateTimer() {
         doReload();   
         timerID = setTimeout("UpdateTimer()", 5000);
      }
    
    
      function keypressed(e){
         if(e.keyCode=='13'){
            doWork();
         }
      }
    //-->
    </script>   
   
    <div id="chatmain">
      <div id="caption">Micro-Chat
      <IMG SRC="icon.gif" ALT="chat" name="chat" width="30" height="30" BORDER="0" align="right" />
       </div>
      
<?php 

if (!isset($_SESSION['nickname']) ){ 
    createForm();
} else  { 
      $name    = isset($_POST['name']) ? $_POST['name'] : "Unnamed";
      $_SESSION['nickname'] = $name;
    ?>
      
     <div id="result">
     <?php 
        $data = file("msg.html");
        foreach ($data as $line) {
        	echo $line;
        }
     ?>
      </div>
      <div id="sender" onkeyup="keypressed(event);">
         Mon message: <input type="text" name="msg" size="30" id="msg" />
         <button onclick="doWork();">j'envoies</button>
      </div>   
<?php            
    }

?> 
</div>

</BODY>
</HTML>

It is a very long code , so I understand if you cannot help me on this.
But if you can give me some tracks to permit me cleaning or link to functions I will move to other pages....?
Thank you

Recommended Answers

All 5 Replies

There's only one "guideline" to avoiding that error. Don't output anything to the page (be that echo, print, print_r, var_dump, etc.) before you call header()

Of course, bu this is easier to know it than to do it. When I have a simple login, it's ok.... but when I have more features on the same page like here, I am lost. How then to preserve the chat and the login etc on the same page ????
you can see here
http://healthforum.uib.no/ohcsurvey/pages-extn/accueil.php
what I aimed at doing, having the module to enrich bibliography, the login and the chat on the same home page....

Member Avatar for diafol

I can't see where your header() statement fits into your code.

You could perhaps place all your php output into variables (above the DTD) and then just echo them out in the relevant places, eg.

<?php
    all your functions and variables 

?>

<!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 http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
<link rel="stylesheet" type="text/css" href="css-accueil.css" />
<title>Accueil</title>
</head>

<body onload="UpdateTimer();">

...(html)...

<?php echo $myVar;?>

...(html)...

<?php echo $myVar2;?>

...(html)...

</body>
</html>

This way, if you need to "header", it can be done before the DTD and before any html output has occurred.

thank you very much ardav, this is the kind of advice I was looking for. I will try your solution this night as I have to learn this anyway before learning to control output buffer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.