views:

300

answers:

3

I've written a script to geocode some points which has a structure basically like this:

//get an unupdated record
$arr_record;
while(count($arr_record) > 0)
{
//strings are derived from $arr_record
geocode($string1);
geocode($string2);
geocode($string3);
array_pop($arr_record);
}

function geocode($string) {
   //if successful
      update($coords)
}

function update($coords) {
   //update the database
   header('Location:http://localhost/thisfile.php')
}

The trouble is that even when the geocode is successful and the database is updated, and teh header resent, the script still goes back into the while loop without reloading the page and starting again on a new record.

Is this normal behaviour for PHP? How do I avoid it behaving like this?

+4  A: 

After header() use die(); to terminate the script and output.

usoban
If this is what the question meant, this is correct.
xenon
The script will output empty body, but header will have other location so brower will redirect user to this location.
usoban
+3  A: 

How do I avoid it behaving like this?

Put exit() after header().

Anti Veeranna
A: 

another effective way is not to send headers directly in a loop. which is not proper (i couldn't find in php.net manual but i remember it was discussed before in phpusenet). it may act unexpected in different php versions. & different apache ver. installations. php as cgi will make problems too.

you can assign it to return as string then you can send header later...

function update($coords) {
       //update the database

       if(statement to understand update is ok){ 
       return 'Location:http://localhost/thisfile.php';
       } else {  
           return false;   
       }
    }

   if($updateresult=update($cords)!=false){ header($updateresult); }

but if i were you... i would try to work ob_start() ob_get_contents() ob_end() because those are the excellent way to control what will be sent to browser. normal mimetypes or headers... whatever. it's better way while working with headers & html output at the same time.

ob_start();  /* output will be captured now */
  echo time();  /* echo test */
  ?>
    print something more...
  <?php  /* tag test */

 /* do some stuff here that makes output. */

$content=ob_get_contents(); 
ob_end_clean();
 /* now everything as output with echo, print or phptags. 
    are now stored into $content variable 
    then you can echo it to browser later 
 */

echo "This text will be printed before the previous code";
echo $content;
risyasin