PHP Page redirect problem - Cannot modify header information

JoeW picture JoeW · Aug 7, 2011 · Viewed 25.4k times · Source

I have a page that displays various elements even if the id it's calling from the database does not exist or was deleted (which throws up all sorts of ugly errors along with search engines continuing to list non-existent pages).

Can you modify the first part of the page code shown below to send a 404 (or at least to projecterror.php which has 404 headers) if $id does not exist? Many thanks!

<?php
include_once("includes/linkmysql.php");
$adda=$_GET['a']; 
$cont=$_GET['c']; 
$select="SELECT * FROM projects where id='$id'";
$qselect = mysql_query($select);
while ($row = mysql_fetch_array($qselect)) { 

The following modification as kindly suggested by Matt Wilson as a result of an original comment by Vivek Goel results in valid entries showing the page correctly but non-existent pages are showing the errors below this modified code:

<?php
include_once("includes/linkmysql.php");
$adda=$_GET['a']; 
$cont=$_GET['c']; 
$select="SELECT * FROM projects where id='$id'";
$qselect = mysql_query($select);
if( mysql_num_rows( $qselect ) === 0 )
{
   header("HTTP/1.1 301 Moved Permanently");
   header( 'Location: http://examplesite.domain/errorpage' ) ;
   exit;
}
while ($row = mysql_fetch_array($qselect)) { 

Errors resulting from the above modifications:

Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 22 
Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 23 Lines 22 and 23 are the two header lines in your example above

Lines 22 and 23 are the two header lines as below:

header("HTTP/1.1 301 Moved Permanently");
header( 'Location: http://examplesite.domain/errorpage' ) ;

Answer

TMS picture TMS · Aug 8, 2011

I have much easier solution for you - it is simple! Just add this command at the very start of the php source:

ob_start();

This will start buffering the output, so that nothing is really output until the PHP script ends (or until you flush the buffer manually) - and also no headers are sent until that time! So you don't need to reorganize your code, just add this line at the very beginning of your code and that's it :-)