2
<?php

ob_start();

echo "<body><p>Hello "

if ($condition) {
   header( "Location: http://www.google.com/" );
   exit;
}

echo " World!</p></body>";
ob_end_flush();

?>

When $condition is true I get this:

<body>Hello

What I want is when $condition will be true then go to Google!!!

I don't know what is happening, can you explain or give me a solution!?

Thanks.

asprin
  • 9,579
  • 12
  • 66
  • 119
CRISHK Corporation
  • 2,948
  • 6
  • 37
  • 52

4 Answers4

3

Just add ob_end_clean(); before the header call.

deviousdodo
  • 9,177
  • 2
  • 29
  • 34
2

Everything should work, just put an ; after echo "<body><p>Hello" and you will be fine..

Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
1

If I were you, I would have started what might go wrong first then do the processing.

An example

$exit_condition_1 = some_value1;
$exit_condition_2 = some_value2;

if($exit_condition_1 == false){

     //Redirect
     //Exit

}

if(!$exit_condition_2){

     //Redirect
     //Exit

}


//start the buffer ob_start()

//show some HTML

//flash the buffer ob_end_clean()

there is no point of starting the buffer then if something goes wrong close it and redirect. Just do value testing at the begining then process the request.

An example: lets say that you want to view a product's info and you have a function that will do that


function view_product($product_id){

   if(!$product = getProductById($product_id)){

        //product does not exist, redirect
   }


   if(the user does not have enough access rights){

     //show a message maybe 
     //redirect
   }


   //everything is alright then show the product info

}
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
thedethfox
  • 1,651
  • 2
  • 20
  • 38
0

To resolve a similar situation where a function was using ob_start() and there was header("Location: http://www.example.com"); after that but erring "already sent...", I replaced the header(... call with

echo "<script> window.location.href = 'https://www.example.com' </script>"

and it worked in that particular case (all that was needed was a just page redirect anyway).

spcsLrg
  • 340
  • 2
  • 11