Cannot modify header information - headers already sent

I have looked at every forum for a answer to the above error. I have tried OB start, removing blank spaces and a number of other hints and nothing works. I can add records or delete them but instead of the completetion message I get the above message. Any help will be greatly appreciated.
[php]<?php

connectDB();

$array_subnav = array ( "view" => "View Projects",
					    "add" => "Add New Projects",
					    "sort" => "Sort Projects",
						"help" => "Help"
					  );

?>

<?php include("classes.php"); ?>
    <?php foreach ($array_subnav as $key=>$val ) { print "
  • $val
  • \n"; } ?>
  • Logout
<?php

	if ($cmd == "view") {
		if ($_GET['msg']) {
			print "<span class=\"msgGreen\">".$_GET['msg']."<br/></span>";
		}

		$id_category = $_POST['id_category'];
		if (!$id_category) {
			$id_category = $_GET['id_category'];
		}
		if (!$subCmd) {
			print "<div style=\"margin-top: 15px; clear:both;\">";
			print "<form action=\"".$_SERVER['REQUEST_URI']."\" method=\"POST\">";
				getCats("selectSubmit");
			print "</form>";
			print "</div>";
		}


		if ($id_category && !$subCmd) {

			$limit = 10;
				if ($numResults != "0") {
			    	//If the query returns results, then do paging

					// get the pager input values
					//$page is declared at the top
					$sql = "SELECT count(*) FROM projectListings WHERE id_category='$id_category'";
				    debugMsg($sql);
				    $resultsCount = mysql_query($sql);
				    $total = mysql_result($resultsCount, 0, 0);

				    // work out the pager values
				    $pager  = Pager::getPagerData($total, $limit, $page);
				    $offset = $pager->offset;
				    $limit  = $pager->limit;
				    $page   = $pager->page;

				    // use pager values to fetch data
				}
				if ($offset < 0) {
					$offset = 0;
				}


			print "<div id=\"results\">";
			$sql = "SELECT * FROM projectListings WHERE id_category='$id_category' ORDER BY sortOrder, name";
			$rs = query($sql,"results");
			while ($row = @mysql_fetch_array($rs) ) {
				$id_project	= $row['id_project'];
				$name		= $row['name'];
				$description= $row['description'];
				$amount		= $row['amount'];
				$contact	= $row['contact'];
				$active		= $row['active'];
				$uniqueId 	= $id_project."_".$name;

				if ($active == "1") {
					$status = "<b>Current Status:</b> On<br/>";
				} else {
					$status = "<b>Current Status:</b> Off<br/>";
				}
				?>

				<h3 class="trigger"><?php print $name; ?></h3>
				<div class="projectBox">
					<?php
						print "$description<br/>
							  <b>Contract Amount:</b> \$".$amount."<br/>
							  <b>Contact:</b> $contact<br/>
							  $status
							  <a class=\"button\" href=\"index.php?cmd=$cmd&subCmd=edit&id_project=$id_project&id_category=$id_category\">Edit</a> &nbsp;<a class=\"button\" href=\"index.php?cmd=$cmd&subCmd=del&id_project=$id_project&id_category=$id_category\">Delete</a><br/>";


					?>
				</div>
				<?php
				unset($id_project);
				unset($name);
				unset($description);
				unset($amount);
				unset($contact);
				unset($active);
			}
			print "</div>";
		} //End <if ($id_category) {>

		if ($subCmd == "edit") {


			if ($_POST['process']) {

				$sql = "SELECT name FROM projectListings WHERE name='".$_POST['name']."'";
				$matches = query($sql,"rowcount");

				if ($matches != "0") {
					$msg = "There is an entry with this name already.<br/>";
				}

				if ($_POST['id_category'] == "0") {
						$msg .= "You must select a category<br/>";
				}

				//Check for other fields that are required
				if (!$_POST['name']) {
					$msg .= "The field \"Project Name\" is required";
				} else {
					if (!checkcharacters($_POST['name'])) {
						$msg .= "The \"Name\" field contains invalid characters. For example, use of the \"&\" symbol is prohibited.";
					}
				}

				if (!$msg) {
					printArray($_POST);
					$iShift = 1;
					while ($iShift < 2) {
						$shift = array_shift($_POST);
					}
					//Take elements from $_POST and update them
					$updateCount = 0;
					$arrayCount = count($_POST);
					foreach($_POST as $key => $val) {
						$update_sql = "UPDATE projectListings SET $key = '".stripInput($val)."' WHERE id_project='".$_GET['id_project']."' LIMIT 1";
						print $update_sql."<br/>";
						query($update_sql,"affected");
					}

					if (!$_POST['active']) {
						$update_sql = "UPDATE projectListings SET active = '0' WHERE id_project='".$_GET['id_project']."' LIMIT 1";
						query($update_sql,"affected");
					}
						header("Location:index.php?cmd=$cmd&id_category=".$_GET['id_category']."&msg=Project Listing for $_POST[name] has been updated");
				}



			}
			print "<span class=\"msgRed\">$msg<br/></span>";
			$sql = "SELECT * FROM projectListings WHERE id_project='".$_GET['id_project']."'";
			$rs = query($sql, "array");
			?>
			<form action="<?php print $_SERVER[REQUEST_URI]; ?>" method="POST" name="theForm">
				<input type="hidden" name="id_product" value="<?php print $_GET['id_project'];?>">
				<input type="hidden" name="process" value="1">
				<?php formTable($rs); ?>
			</form>

			<?php
		}

		if ($subCmd == "del") {
			//Get job name

				$sql = "SELECT name FROM projectListings WHERE id_project='".$_GET['id_project']."'";
				$rs = query($sql,"array");

				if ($_GET['process'] != "1") {
					print "Deleting the project titled <span style=\"color: #bc230f;\">\"".$rs['name']."\"</span> is irreversible.<br/>";
					print "Do you wish to continue?<br/>";
					print "<a class=\"button\" href=\"".$_SERVER['REQUEST_URI']."&process=1\">Yes</a> &nbsp;&nbsp; <a class=\"button\" href=\"index.php?cmd=view&id_category=".$_GET['id_category']."\">No</a>";
				} else {
					//Do deletion
					$DELETE_sql = "DELETE FROM projectListings WHERE id_project='".$_GET['id_project']."' LIMIT 1";
					$rs_delete = query($DELETE_sql,"affected");
					if ($rs_delete == 1) {
						header("Location:index.php?cmd=view&id_category=".$_GET['id_category']."&msg=The project listing, ".$rs['name'].", has been deleted");
					}
			}
		}
	}

	if ($cmd == "add") {
		if ($_GET['msg']) {
			print "<span class=\"msgGreen\">".$_GET['msg']."<br/></span>";
		}

		if ($_POST['process']) {
			$shift = array_shift($_POST);
			//Make sure there is no entry already for this title
			$sql = "SELECT name FROM projectListings WHERE name='".$_POST['name']."'";
			$matches = query($sql,"rowcount");

			if ($matches != "0") {
				$msg = "There is an entry with this name already.<br/>";
			}

			if ($_POST['id_category'] == "0") {
					$msg .= "You must select a category<br/>";
			}

			//Check for other fields that are required
			if (!$_POST['name']) {
				$msg .= "The field \"Project Name\" is required";
			} else {
				if (!checkcharacters($_POST['name'])) {
					$msg .= "The \"Name\" field contains invalid characters. For example, use of the \"&\" symbol is prohibited.";
				}
			}




			if (!$msg) {
				//Do the insert
				$sql_insert = "INSERT INTO projectListings (";
				$count = count($_POST);
				$current = 1;

				foreach($_POST as $key => $val) {
					if ($current < $count) {
						$sql_insert .= "$key,";
						$current++;
					} else {
						$sql_insert .= "$key";
						$current = 1;
					}
				}

				$sql_insert .= ") VALUES (";

				foreach($_POST as $val) {
					if ($current < $count) {
						$sql_insert .= "'".stripInput($val)."',";
						$current++;
					} else {
						$sql_insert .= "'".stripInput($val)."'";
					}
				}

				$sql_insert .= ")";

				query($sql_insert,"results");

				header("Location:index.php?cmd=add&msg=".$_POST['name']." has been successfully added");

			}


		}
		print "<span class=\"msgRed\">$msg</span>";
		?>
		<form action="index.php?cmd=add" method="POST" name="theForm">
			<input type="hidden" name="process" value="1">
			<?php formTable($_POST); ?>
		</form>

		<?php

	}

	if ($cmd == "sort") {
		if ($_GET['msg']) {
			print "<span class=\"msgGreen\">".$_GET['msg']."<br/></span>";
		}

		$id_category = $_POST['id_category'];
		if (!$id_category) {
			$id_category = $_GET['id_category'];
		}
		?>
		<SCRIPT LANGUAGE="JavaScript">
		<!-- Original:  Roelof Bos ([email protected]) -->
		<!-- Web Site:  http://www.refuse.nl -->

		<!-- This script and many more are available free online at -->
		<!-- The JavaScript Source!! http://javascript.internet.com -->

		<!-- Begin
		function move(index,to) {
		var list = document.form.list;
		var total = list.options.length-1;
		if (index == -1) return false;
		if (to == +1 && index == total) return false;
		if (to == -1 && index == 0) return false;
		var items = new Array;
		var values = new Array;
		for (i = total; i >= 0; i--) {
		items[i] = list.options[i].text;
		values[i] = list.options[i].value;
		}
		for (i = total; i >= 0; i--) {
		if (index == i) {
		list.options[i + to] = new Option(items[i],values[i + to], 0, 1);
		list.options[i] = new Option(items[i + to], values[i]);
		i--;
		}
		else {
		list.options[i] = new Option(items[i], values[i]);
		   }
		}
		list.focus();
		}
		function submitForm() {
		var list = document.form.list;
		var theList = "&";
		// start with a "?" to make it look like a real query-string
		for (i = 0; i <= list.options.length-1; i++) {
		//theList += i + "=" + list.options[i].value;
		theList += list.options[i].value + "=" + encodeURI(list.options[i].text);
		// a "&" only BETWEEN the items, so not at the end
		if (i != list.options.length-1) theList += "&";
		}
		location.href = document.form.action + "&id_category=<?php print $id_category; ?>&beginSort=1" + theList;
		}
		//  End -->
		</script>

		<?php


			if ($_GET['beginSort'] == "1") {
				print "true<br/>";
				printArray($_GET);

				$arrGET = $_GET;
				$iShift = 1;
				while($iShift <= 3) { //Number of times to shift the array to get only the sorted items
					$arrShift = array_shift($arrGET);
					$iShift++;
				}
				printArray($arrGet);
				foreach($arrGET AS $key => $val) {
					$updateSQL = "UPDATE projectListings SET sortOrder='$key' WHERE name='$val' LIMIT 1";
					$updateResults = query($updateSQL,"results");
				}
				header("location:index.php?cmd=sort&msg=Your projects have been successfully sorted");
			}



		?>




		<table border="0" cellpadding="2" cellspacing="0" align="center">
			<form method="POST" action="index.php?cmd=sort" name="selectCategory">
			<tr><td colspan="2"><?php getCats("selectSubmit"); ?>
				</td></tr>
			</form>
			<?php
			 	if ($id_category) { ?>
					<form method="GET" action="index.php?cmd=sort" name="form">

					<tr>
						<td>
							<?php
								$sql = "SELECT * FROM projectListings WHERE id_category='$id_category' ORDER BY sortOrder, id_project";
								$result = mysql_query($sql) or die(mysql_error());

								if(mysql_num_rows($result)!="0") {
									print "<select name=\"list\" size = \"10\" style=\"width: 500px;\">";
									$iOption = 0;
									while ($row = mysql_fetch_array($result)) {
										print "	<option value=\"$iOption\">".$row['name']."</option>";
										$iOption++;
									}
									print "</select>";
								} else {
									print "<select name=\"list\" size = \"10\" DISABLED>";
									print "	<option>No projects are added for this category</option>";
									print "</select>";
								}

							?><br/>
							<input type="button" value="Save Changes" class="inputButton" onClick="submitForm()">
						</td>
						<td valign="top">
							<input type="button" value="Up" onClick="move(this.form.list.selectedIndex,-1)" class="inputButton" style="width: 50px;"><br><br>
							<input type="button" value="Down" onClick="move(this.form.list.selectedIndex,+1)" class="inputButton" style="width: 50px;">
						</td>
					</tr>
					</form>
				<?php } else { ?>
					<form method="GET" action="<?PHP print $_SERVER['REQUEST_URI'];?>" name="form">
					<tr>
						<td>
							<select name="list" size="10" style="width: 500px;" disabled>
								<option>You must select a category above</option>
							</select>
							<br/>
								<input type="button" value="Save Changes" class="inputButton" onClick="submitForm()">
						</td>
						<td valign="top">
							<input type="button" value="Up" onClick="move(this.form.list.selectedIndex,-1)" class="inputButton" style="width: 50px;"><br><br>
							<input type="button" value="Down" onClick="move(this.form.list.selectedIndex,+1)" class="inputButton" style="width: 50px;">
						</td>
					</tr>
					</form>
				<?php } ?>
		</table>

		<?php
	}

	if ($cmd == "help") {
		?>
		<h3 class="trigger">Adding a New Project</h3>
		<div class="projectBox">
			<ol class="instructions">
				<li>Click on "Add New"</li>
				<li>Choose which category the project listing belongs. Either "Pipeline / Facilities projects" or "Oilfield Services projects"</li>
				<li>The only required field is the <b>Project Name</b>. Make sure this is entered.</li>
				<li>Continue filling in the rest of the information as necessary.</li>
				<li>The last item decides whether the project will be displayed. If you would like to save the listing for another time or have not
					completed entering it, leave the <b>Display On/Off</b> box <i>unchecked</i>. If you would like it to display immediately, click the
					box so a checkmark appears</li>
			</ol>
		</div>

		<h3 class="trigger">Editing or Deleting a Project</h3>
		<div class="projectBox">
			<ol class="instructions">
				<li>Click on "View"</li>
				<li>Choose which category the project is under. Either "Pipeline / Facilities projects" or "Oilfield Services projects"</li>
				<li>Locate the project in the listing and click on the name.</li>
				<li>Below the information for the project, there are two buttons, "Edit" and "Delete". </li>
				<li>Clicking on "Edit" will bring you to a screen which resembles the "Add New" screen. Edit any changed fields and click "Save" to keep your changes.</li>
				<li>Clicking on "Delete" will bring you to a screen which asks if you are sure you would like to proceed with the deletion. Answer "Yes" or "No"
			</ol>
		</div>

		<h3 class="trigger">Sorting Project Listings </h3>
		<div class="projectBox">
			This allows for you to customize the order in which you would like the projects to be listed on the Projects Listing page. You can
			sort them within their categories.
			<ol class="instructions">
				<li>Click on "Sort Projects"</li>
				<li>Choose which category you would like to sort</li>
				<li>Highlight the desired listing you would like to re-sort.</li>
				<li>After highlighting the listing, use the "Up" and "Down" buttons on the right hand to side to move the listing further up or down the list</li>
				<li>Once the desired location is set, you may sort another project by repeating steps 3 & 4.</li>
				<li>After all of your listings are in the order you like, click the "Save Changes" button.</li>
				<li>Changes will be reflected immediately on the Project Listings page</li>
			</ol>
		</div>
		<?php

	}


?>
[/php]

Well, perhaps you do not understand what a header is… First, let’s take a HTML page without any type of programming on it. It is laid out something like this:

You will see that the “HEADER” is outside the “BODY” of the page. This is important! So, in the HTML above, the header is BEFORE the body of the file. In PHP ALL headers must ( MUST ! ) be before the body of the page. Since PHP is handled SERVER-SIDE only, you can NOT post any body/HTML/Javascript/etc to the page before executing the PHP header.

In your code posted, just a very few lines down, you post HTML to the browser:

Therefore PHP can NOT execute any further headers.

Also, just before you execute the header, you print out data. This data will never be seen if you switched pages directly after printing the data. That does not make sense. And, of course printed data means “body” so you can not use headers after a print anyways!

Now, how to fix all that? You can place Javascript in the “rendered” page with PHP that would switch pages as long as the logic was figured out correctly. But, that can be hard to follow. Normally if you are planning to switch pages, you do all the calculations and then under the correct condition, you either display a page or switch to the other page. You normally do not display and switch.

Hope that all makes sense to you. Good luck…

Thanks for the very good explantion. This coding was run separately, not from the website, so it probably never worked in the first place. So I guess I will have to start figuring out what the programmer was trying to do and redo some of the PHP coding. Thanks for the help.

Well, glad you understood the previous post… (Header Tutorial?)

I think the best way would be to take that page you posted and break it done it what it actually does.
Then, go back and make sure the section that includes a header call is at the top of the page.
In other words, you CAN do header calls if it is before the HTML’s header. So, this sample will work:

<?PHP if(cond) { header("Location: somepage.php"); } ...Some HTML header stuff... <?PHP some code with NO header calls! ?>

some displayed html lines

Just a sample, don’t try it. LOL… I wanted to show you a basic layout for using PHP to call headers. Another way is to call it from a posted form. You can have a form that calls out to another PHP page. In that PHP handle your php code without HTML and then just back to the resulting HTML page…

Hope that helps too! Good luck with your project!

That is what I started doing yesterday after your post and I am having some luck. Again thanks for the help.

Great! Good luck with it. Ask away if you need more help. And let us know if you solve it all…

Seeing as my time is so limited, because of all the projects I have to do, I tried something as simple as replacing the Header statements with something similar to this:[php]print(“Project: “.$_POST[‘name’].” has been successfully added!”);[/php]. This works like I want so later on when I have more time to study maybe I can figure out what the person who wrote this code was trying to do with the Header code.

Okay, but, I just think it is the location in the header.

Well, I think you problem is the header line does not have quotes around it. There must be quotes around all of the location… So, this line:

header(“Location:index.php?cmd=$cmd&id_category=”.$_GET[‘id_category’]."&msg=Project Listing for $_POST[name] has been updated");

Just needs some quotes around the entire header. You start the quote and stop it after the word category!
So, it never sees the rest. Try this instead:

header("‘Location:index.php?cmd=$cmd&id_category=" . $_GET[‘id_category’] . "&msg=Project Listing for " . $_POST[name] . " has been updated’");

But, we can look at it later on as you want to…

I tried the changed you recommended and I get the same error message I was getting before I change the line.

Well, since you found a work around, I guess we can close this post.
You can open a new one later on when you get caught up on your other work.
If you want to private-message me with posts of all the files, I can look at it another day
and see if it works on my server. (I will just dummy out the database parts…)

But, at least it is working one way for you.

Sponsor our Newsletter | Privacy Policy | Terms of Service