Home > Software engineering >  PHP: Unable to redirect to another page under a condition
PHP: Unable to redirect to another page under a condition

Time:12-03

I'm having troubles in using a redirect in a PHP page. Basically, I'm using the following function to redirect:

function redirect($url) {
    ob_start();
    header('Location: '.$url);
    ob_end_flush();
    die();
}

Then, at the beginning of the PHP page, I'm checking for a var value. If that's over a threshold, I redirect to another page:

<?php 
. . .
if (var >= 100) {
   redirect('error1.html');
}
?>  
<html>
 <body>
  <!-- HTML page here -->
 </body>
</html>

Although the var is over 100 (it is printed on the screen), no redirect takes place. Any idea why? Is it because there's HTML content included in the page?

CodePudding user response:

you cant use "if (var...)" cause var is a protected term.

I don't know if is this an example but the correct way to do what you like, should be:

    function redirect( $code, $url ) {

        // Test code
        if( $code >= 100 ){
          
          // If you will redirect you don't need OB function
          // ob_start(); ** removed
          
          // Redirect
          header('Location: '.$url);
          
          // ob_end_flush(); ** removed
          exit(); // better use function exit then die
        
        } // end if test code
    }

    ...

    <?PHP 
    
        redirect( $code, 'error1.html');
    ?>
´´´

Hope help you ! ;)
  •  Tags:  
  • php
  • Related