[PHP problem] - Cannot modify header information - headers already sent by ...

soulblader_86

Supremacy Member
Joined
Sep 28, 2007
Messages
9,012
Reaction score
0
Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\xampp\crm\sidebar.php:73) in D:\xampp\htdocs\xampp\crm\confirmCustomer.php on line 120

This is my side bar PHP

It happen when I add customer from customer page

this is my sidebar php

PHP:
<?php include('config.php') ?>
 <link rel="stylesheet" type="text/css" href="style.css"/>
<div id = "sandy">
 <p class = "searchbox">
   <input class="search" placeholder="Search Company" />
 </p>
 
 <ul class="list">
	<?php
	$qry = "SELECT * FROM customer order by DateCreated DESC";
 $result = mysql_query($qry);
	$num = mysql_num_rows($result);
	if($num >=1)
	{
		while($row = mysql_fetch_array($result))
		{?>
         <li>
         
<a class="search" href="customer.php?id=<?php echo $row["CustomerID"]?>"><span class="name"><?php echo $row["CompanyName"]?></span></a>                          
 </li>
        <?php
             
 }
 }
  ?>  
</ul>  

</div>

    <!-- Start of List.js stuff -->
<script src="list.js"></script>

<script type="text/javascript">

        /*
        * LOVELY THINGS
        */

var options = {
    valueNames: [ 'name' ]
 };

var featureList = new List('sandy', options);

$('#filter-games').click(function() {
featureList.filter(function(item) {
if (item.values().category == "Game") {
return true;
 } else {
 return false;
 }
 });
return false;
});

 $('#filter-beverages').click(function() {
featureList.filter(function(item) {
if (item.values().category == "Beverage") {
 return true;
} else {
    return false;
  }
 });
            return false;
        });
        $('#filter-none').click(function() {
            featureList.filter();
            return false;
        });
    </script>
    <!-- End of List.js stuff -->

this is my confirmcustomer.php

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=utf-8" />
<title>Untitled Document</title>
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

 <script>
 
  $(function() {
    $( "#tabs" ).tabs();
  });
  </script>
    <link rel="stylesheet" type="text/css" href="style.css" />


</head>

<body><div id="main_container"> 

<table width="980" border="1" id="main_table" cellpadding="5" cellspacing="5">
  <tr>
    <td colspan="2" height="100"><?php include('header.php') ;?></td>
  </tr>
  <tr>
    <td width="200" height="300" valign="top" id="sidebar"><?php include('sidebar.php') ;?></td>
  <td width="696" valign="top" id="width">
<!-- Start of content -->

          <?php 
	
		  if (!empty($_FILES["file"]["name"]))
		  {
		  
$filename = $_FILES["file"]["name"];
$allowedExts = array("gif", "jpeg", "jpg", "png");
 $extension = substr ($filename, strpos($filename, '.')+ 1);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2097152)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
	?>
<br>
<a href="addCustomer.php"><img src="images/back1.png" width="42" height="41" /></a>

<?php

	
	die();
    }
  else
    {


      move_uploaded_file($_FILES["file"]["tmp_name"],
      "images/" . $_FILES["file"]["name"]);
   
      
    }
  }
else
  {
  echo "Invalid image file";
  ?>
<br>
<a href="addCustomer.php"><img src="images/back1.png" width="42" height="41" /></a>

<?php

  die();
  }
	  
		  
  }
		  
		  
		  

		  
 $image = "images/" . $_FILES["file"]["name"];
 $name =$_POST["name"];
 $address=$_POST["address"];
 $industry = $_POST["industry"];
 $employees = $_POST["employees"];
 $netprofit= $_POST["netprofit"];
 $industry= $_POST["industry"];
 $contact = $_POST["contact"];
  $turnover = $_POST["turnover"];
  $createdBy = $_POST["createdby"];
  $website = $_POST["website"];
  $date = $_POST["date"];

$qry = "Select * FROM Customer Where CompanyName='$name'";
$result = mysql_query($qry);
$num = mysql_num_rows($result);
	if($num >=1)
	{
		echo "Company was previously added in the database";
	}
else
{
 
 mysql_query("INSERT into customer(OfficeNumber,CompanyName,Turnover,NetProfit,Industry, Employees, Address, Image, CreatedBy, DateCreated, Website)values ('$contact', '$name' , '$turnover', '$netprofit', '$industry', '$employees', '$address','$image','$createdBy','$date','$website')");

$qry = "select * from customer where CompanyName = '$name'";
	$result = mysql_query($qry);
	$num = mysql_num_rows($result);
	if($num >=1)
	{
  header("Location: customer.php?add=1");
	
}

else
{
//  header("Location: customer.php?add=0");
}
	

?>
<br>
<a href="addCustomer.php"><img src="images/back1.png" width="42" height="41" /></a>

<?php
}
?>
  <!-- End of Content -->
  </td>
  </tr>
  <tr>
    <td colspan="2" height="20"><?php include('footer.php') ;?></td>
  </tr>
</table>
</div>
</body>
</html>

what does header mean?
 

hw.tan

Junior Member
Joined
Aug 6, 2011
Messages
19
Reaction score
0
See HTTP Headers for Dummies | Nettuts+

In short, they are information that the web server send regarding the HTTP request.
For PHP, headers are automatically sent whenever there are output needs to be send to the client.

I did not really read through your code, but you have a 'header("Location: customer.php?add=1")' which occurs after the first line of output.

Use ob_start to buffer the output.
 

soulblader_86

Supremacy Member
Joined
Sep 28, 2007
Messages
9,012
Reaction score
0
See HTTP Headers for Dummies | Nettuts+

In short, they are information that the web server send regarding the HTTP request.
For PHP, headers are automatically sent whenever there are output needs to be send to the client.

I did not really read through your code, but you have a 'header("Location: customer.php?add=1")' which occurs after the first line of output.

Use ob_start to buffer the output.

what will happen is I use ob_start?
 

NSforSG

High Supremacy Member
Joined
Nov 17, 2010
Messages
34,250
Reaction score
2
Can you post your header.php here, withou all the sensitive information?
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\xampp\crm\sidebar.php:73) in D:\xampp\htdocs\xampp\crm\confirmCustomer.php on line 120

This is my side bar PHP

It happen when I add customer from customer page

this is my sidebar php


this is my confirmcustomer.php

PHP:
...
		  
 $image = "http://forums.hardwarezone.com.sg/images/" . $_FILES["file"]["name"];
 $name =$_POST["name"];
 $address=$_POST["address"];
 $industry = $_POST["industry"];
 $employees = $_POST["employees"];
 $netprofit= $_POST["netprofit"];
 $industry= $_POST["industry"];
 $contact = $_POST["contact"];
  $turnover = $_POST["turnover"];
  $createdBy = $_POST["createdby"];
  $website = $_POST["website"];
  $date = $_POST["date"];

$qry = "Select * FROM Customer Where CompanyName='$name'";
$result = mysql_query($qry);
$num = mysql_num_rows($result);
	if($num >=1)
	{
		echo "Company was previously added in the database";
	}
else
{
 
 mysql_query("INSERT into customer(OfficeNumber,CompanyName,Turnover,NetProfit,Industry, Employees, Address, Image, CreatedBy, DateCreated, Website)values ('$contact', '$name' , '$turnover', '$netprofit', '$industry', '$employees', '$address','$image','$createdBy','$date','$website')");

$qry = "select * from customer where CompanyName = '$name'";
	$result = mysql_query($qry);
	$num = mysql_num_rows($result);
	if($num >=1)
	{
  header("Location: customer.php?add=1");
	
}

else
{
//  header("Location: customer.php?add=0");
}
	
...

what does header mean?

The big concept of HTTP request and response model consists of headers and content body.

When a HTTP requests reaches your web server, it looks similarly to this
Code:
GET /index.html HTTP/1.1
[COLOR="Green"][B]Host: www.example.com
Cookie: name=value; name2=value2
Accept: */*[/B][/COLOR]

The HTTP response from your web server looks similarly to this too
Code:
HTTP/1.1 200 OK
[COLOR="Green"][B]Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09-Jun-2021 10:18:14 GMT[/B][/COLOR]
 
<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>

Those highlighted in GREEN are headers of the HTTP request and response. They MUST be sent out in a HTTP request or response BEFORE the content of the request or response are sent.

In your case, PHP's header function will attempt to attach a header for sending out, but this function is invoked AFTER you have already send out the content of your HTTP response, which consist of all the HTML text above it. Under the HTTP request and response model, no headers are allowed to be sent after the body are already sent.

2 ways to solve your problem
1) Shift your php code logics to determine whether to send your HTTP response header to the start of the PHP application.
2) Use ob_start function to start an internal buffer. You may call as many headers as you wish within since PHP will not send out the body to the web server until you invoke ob_end_flush function.

However looking at your spaghetti codes, I highly recommend you resolve your problem from a holistic approach. Go and find a php template engine and store your HTML templates instead of littering your PHP codes all over the place.

The way you are doing this project is not only bad design, but also hard for others or even yourself to follow up in months to come.

There are a few PHP template engine, and the first that I have come across since the dawn of my PHP knowledge is PHP Template Engine | Smarty. Learn how template engines are used in web development and not only will it help to solve the problem you are having now, it will encourage better coding skill and better quality work. For more template engines options, refer to http://en.wikipedia.org/wiki/Template_engine_(web)

For any web developer, go and learn the correct web development approach known as Model-View-Controller(MVC). This model of web development is applicable across all programming languages and platforms. It helps in ensuring good segregation between codes and contents as well as helps in security management, operations and maintenance.

Working in the Enterprising world, I always hear people saying PHP encourage security breaches and hence not suitable as a platform compared to dotNET or Java. I'm officially trained in Java, but I don't find PHP less in security. It's the developers that doesn't understand how to structure your web application properly and securely that results in security breaches. So please start by programming properly in PHP, or else you will never knows what hit you when they do.
 
Last edited:

stupidbodo

Junior Member
Joined
Mar 26, 2010
Messages
89
Reaction score
0
The big concept of HTTP request and response model consists of headers and content body.

When a HTTP requests reaches your web server, it looks similarly to this
Code:
GET /index.html HTTP/1.1
[COLOR="Green"][B]Host: www.example.com
Cookie: name=value; name2=value2
Accept: */*[/B][/COLOR]

The HTTP response from your web server looks similarly to this too
Code:
HTTP/1.1 200 OK
[COLOR="Green"][B]Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09-Jun-2021 10:18:14 GMT[/B][/COLOR]
 
<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>

Those highlighted in GREEN are headers of the HTTP request and response. They MUST be sent out in a HTTP request or response BEFORE the content of the request or response are sent.

In your case, PHP's header function will attempt to attach a header for sending out, but this function is invoked AFTER you have already send out the content of your HTTP response, which consist of all the HTML text above it. Under the HTTP request and response model, no headers are allowed to be sent after the body are already sent.

2 ways to solve your problem
1) Shift your php code logics to determine whether to send your HTTP response header to the start of the PHP application.
2) Use ob_start function to start an internal buffer. You may call as many headers as you wish within since PHP will not send out the body to the web server until you invoke ob_end_flush function.

However looking at your spaghetti codes, I highly recommend you resolve your problem from a holistic approach. Go and find a php template engine and store your HTML templates instead of littering your PHP codes all over the place.

The way you are doing this project is not only bad design, but also hard for others or even yourself to follow up in months to come.

There are a few PHP template engine, and the first that I have come across since the dawn of my PHP knowledge is PHP Template Engine | Smarty. Learn how template engines are used in web development and not only will it help to solve the problem you are having now, it will encourage better coding skill and better quality work. For more template engines options, refer to http://en.wikipedia.org/wiki/Template_engine_(web)

For any web developer, go and learn the correct web development approach known as Model-View-Controller(MVC). This model of web development is applicable across all programming languages and platforms. It helps in ensuring good segregation between codes and contents as well as helps in security management, operations and maintenance.

Working in the Enterprising world, I always hear people saying PHP encourage security breaches and hence not suitable as a platform compared to dotNET or Java. I'm officially trained in Java, but I don't find PHP less in security. It's the developers that doesn't understand how to structure your web application properly and securely that results in security breaches. So please start by programming properly in PHP, or else you will never knows what hit you when they do.


superb answer, this is the kind of reply that gets UPVOTE with GREEN TICKS on SO.

anyway soulblader if you want to start writing modular, more structured code you can start by writing unit test.

Writing unit test forces you to think twice about the way you write your code and forces you to break your code into tiny bits instead of huge chunks.
 
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top