When i am using
header(location: url);
in meddle or end of my php script or html
i am facing following problem
Header already sent.

while when i am using

header(location: url);
in the start of page it works fine,

Is there any redirect('url') function in php like asp or any other alternitive that i can redirect to a page instead of using header() function becuase it is not working when we call it from meddle of html page

    Hi,

    Why do you want the redirect in the middle of the page? Can you explain a bit what is it you are tryin gto do?

      well,
      I am using header() in middle of page sometimes

      What you should do is:
      Write your pages, so all HTML Output comes later, at the end of page

      This way, you Will NOT Send any Header before a header() redirect.

      One of these examples below would produce
      Warning: headers already sent!
      if was a header redirect.

      Newbies often start a php page like this

      <?php
      
      echo '<html><body>'; // Any echo output will SEND HEADER!
      
      // here comes some php script, 
      //and maybe header(location)
      
      ?>
      Hello world!
      </body></html>

      while good php coders would do it like this

      <?php
      
      $html_start = '<html><body>'; // make a variable, instead of echo
      
      // here comes some php script, 
      //and maybe header(location)
      
      ?>
      <?php echo $html_start; ?>
      Hello world!
      </body></html>

        Look to following code

        
        <?php 
        
        //error_reporting(0);
        
         session_start();
         if( $_SESSION['name'] == '')
         {
           echo "You are not authorized user";
           header("location: test.htm");
         }
        
          echo "<b>Welcome, ".$_SESSION['name']." </b> <br> ";
          echo date('d/m/Y  H:i:s', $_SESSION['time'])."<br>";
        
        ?>
        
        

        When i executed above code i faced following warning message

        You are not authorized user
        Warning: Cannot modify header information - headers already sent by (output started at C:\cgi-bin\sch\login.php:8) in C:\cgi-bin\sch\Demo.php on line 9

          Hi Jehan,

          I can see what you are trying to do. However, the use of header("location: test.htm"); implies the you want the user to be instantly forwarded to test.htm. In which case, there is no point in printing the error message as the user will never see it. If you do intend to instantly forward the user, then delete the error message echo.

          However, if you want to show the user the error message, and then forward them a few seconds afterwards, you should be using somthing like this in your HTML code:

          <meta http-equiv="refresh" content="2;url=http://webdesign.about.com">
          

          Note: You should always call exit(0); after redirecting by sending headers (the former method).

            Write a Reply...