Wednesday 27 January 2016

PHP Page redirect problem - Cannot modify header information




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!




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:



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




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 :-)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...