20

No idea why this is not working. Here is the code:

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    echo $_POST['cancel'];
}

Instead of redirecting the page, this output's cancel to the webpage. It skipped over the redirect. Why? How can I fix this? page1.php is a real page located in the same folder as the current page. The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.

John S
  • 386
  • 1
  • 3
  • 17
  • 4
    Don't echo anything afterwards; do an `exit()` to terminate the script. (You shouldn't output anything after having issued that header) – Pekka Jan 20 '14 at 04:18
  • 2
    It's because you've already sent data to the browser in this context and therefore the `headers have been sent`. Turn on your `error_reporting` to get this answer in the future. – Ohgodwhy Jan 20 '14 at 04:18
  • @Pekka웃 That isn't the source of the problem. You can echo anything you want afterwards... it just doesn't make any sense because the browser won't show it, so you're just wasting bytes. – Brad Jan 20 '14 at 04:19
  • @JohnS It's not possible to help you since you don't show us any debugging output. What do you see when you `var_dump($_POST)`? – Brad Jan 20 '14 at 04:20
  • 1
    @Pekka웃 using echo is fine, I doubt the condition isn't sufficed – Mr. Alien Jan 20 '14 at 04:20
  • @Pekka웃 I do not see any reasons, why it shouldn't work, if OP sends data afterwards. It doesn't matter. What matters, that if OP sends data *before*. – BlitZ Jan 20 '14 at 04:20
  • 2
    Error reporting is on. No errors. If I take the echo statement out, then it continues with the rest of the page anyways. I included the echo statement to show the if statement is executing. – John S Jan 20 '14 at 04:20
  • var_dump shows value is 'cancel' of type string – John S Jan 20 '14 at 04:21
  • @JohnS did you sent any data to client (spaces included) before `header(...)` ? – BlitZ Jan 20 '14 at 04:22
  • @Mr. Alien, HAL9000 - true. – Pekka Jan 20 '14 at 04:22
  • No. No data sent to client. None. – John S Jan 20 '14 at 04:23
  • Have you tried to use absolute URL path to page? – BlitZ Jan 20 '14 at 04:24
  • 3
    @JohnS try this `header('Location: ABSOLUTE_URL_HERE', true, 302);` – Mr. Alien Jan 20 '14 at 04:25
  • I just tried the absolute url. h t t p : / / l o c a l h o s t/ etc. (without the spaces). It still echo's out the statements and does not redirect. – John S Jan 20 '14 at 04:27
  • @JohnS Could you, please, provide entire script? Looks like those lines is not the ones, that produces an issue, that you encountering. – BlitZ Jan 20 '14 at 04:29
  • Does sessions have any affect on this issue? I start the session AFTER the above code, just incase the session affects the header information. – John S Jan 20 '14 at 04:30
  • @JohnS yes, bring session at the very top of the page – Mr. Alien Jan 20 '14 at 04:32
  • I had multiple header(location:example.php); statements on the same page. I'm not sure why this was an issue exactly, but this is the culprit. – John S Jan 20 '14 at 05:04
  • Try adding ob_start(); at the top of the code i.e. before the include statement. – Raugaral Nov 19 '15 at 15:26

14 Answers14

26

This is likely a problem generated by the headers being already sent.

Why

This occurs if you have echoed anything before deciding to redirect. If so, then the initial (default) headers have been sent and the new headers cannot replace something that's already in the output buffer getting ready to be sent to the browser.

Sometimes it's not even necessary to have echoed something yourself:

  • if an error is being outputted to the browser it's also considered content so the headers must be sent before the error information;
  • if one of your files is encoded in one format (let's say ISO-8859-1) and another is encoded in another (let's say UTF-8 with BOM) the incompatibility between the two encodings may result in a few characters being outputted;

Let's check

To test if this is the case you have to enable error reporting: error_reporting(E_ALL); and set the errors to be displayed ini_set('display_errors', TRUE); after which you will likely see a warning referring to the headers being already sent.

Let's fix

Fixing this kinds of errors:

  • writing your redirect logic somewhere in the code before anything is outputted;
  • using output buffers to trap any outgoing info and only release it at some point when you know all redirect attempts have been run;
  • Using a proper MVC framework they already solve it;

More

MVC solves it both functionally by ensuring that the logic is in the controller and the controller triggers the display/rendering of a view only at the end of the controllers. This means you can decide to do a redirect somewhere within the action but not withing the view.

Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51
23

I have experienced that kind of issue before and now I'm not using header('Location: pageExample.php'); anymore, instead I'm using javascript's document.location.

Change your:

header('Location: page1.php');

To something like this:

echo "<script type='text/javascript'> document.location = 'page1.php'; </script>";

And what is the purpose of echo $_POST['cancel']; by the way?, just delete that line if what you want is just the redirection. I've been using that <script> every time and it doesn't fail me. :-)

Kiel Labuca
  • 1,223
  • 9
  • 13
13

Use @obstart or try to use Java Script

put your obstart(); into your top of the page

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    exit();
}

If you use Javascript Use window.location.href

window.location.href example:

 if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
    {
        echo "<script type='text/javascript'>window.location.href = 'page1.php';</script>"
        exit();
    }
Padmanathan J
  • 4,614
  • 5
  • 37
  • 75
  • A header redirect will only send the HTTP headers specifying the new URL you have been redirected to. Using JS is a workaround -- it means having to receive/parse/run a page (HTTP headers + some content) and then the JavaScript will trigger a new request for which to receive/parse/run another page. – Mihai Stancu Jan 20 '14 at 08:33
11

I had also the similar issue in godaddy hosting. But after putting ob_start(); at the beginning of the php page from where page was redirecting, it was working fine.

Please find the example of the fix:

fileName:index.php

<?php
ob_start();
...
header('Location: page1.php');
...
ob_end_flush();
?>
IRSHAD
  • 2,855
  • 30
  • 39
10

I had similar problem... solved by adding ob_start(); and ob_end_flush(); ...

<?php 
ob_start();


require 'engine/vishnuHTML.class.php';
require 'engine/admin/login.class.php';

$html=new vishnuHTML();
 (!isset($_SESSION))?session_start():"";

/* blah bla Code
...........
...........
 */

</div>
</div>
<?php
}



ob_end_flush();
?>

Think of ob_start() as saying "Start remembering everything that would normally be outputted, but don't quite do anything with it yet."

ob_end_clean() or ob_flush(), which either stops saving things and discards whatever was saved, or stops saving and outputs it all at once, respectively.

VishnuKumar Pv
  • 167
  • 1
  • 13
5

For me also it was not working. Then i try with javascript inside php like

echo "<script type='text/javascript'>  window.location='index.php'; </script>";

This will definitely working.

Hariharaselvam
  • 163
  • 1
  • 9
  • sometimes it won't work, you have to put ob_start/end. see my post, you will get something else. – IRSHAD Sep 20 '17 at 07:34
4

Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.

UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.

John S
  • 386
  • 1
  • 3
  • 17
4

Neer to specify exit code here so php not execute further

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');        
    exit(0); // require to exit here 
}
Niketan Raval
  • 479
  • 2
  • 10
3

Try adding

ob_start();

at the top of the code i.e. before the include statement.

Raugaral
  • 1,303
  • 13
  • 25
3

Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.

Abhi Burk
  • 2,003
  • 1
  • 14
  • 21
2

Be very careful with whitespace and other stuff that may affect the "output" already done. I certainly know this but still suffered from the same problem. My whole "Admin.php"-file had some spaces after the closing php-tag ?> down the bottom on the last row :)

Easily discovered by adding...

error_reporting(E_ALL);

...which told me which line of code that generated the output.

anoraq
  • 515
  • 7
  • 9
1

Try this, Add @ob_start() function in top of the page,

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    exit();
}
Krish R
  • 22,583
  • 7
  • 50
  • 59
1

Use the following code:

if(isset($_SERVER['HTTPS']) == 'on')
{

    $self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    ?>

     <script type='text/javascript'>
     window.location.href = 'http://<?php echo $self ?>';
     </script>"
     <?php

     exit();
}
?>
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
0

put < ?php tag on the top of your file (starting on frist line of document)

not:

--- Blank space or something ---
<?php

but:

<?php
..your code
header('Location: page1.php');
...
Damianos17
  • 37
  • 8
  • 1
    Are you kidding? I copied the following from my original post, “The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.” It looks like I didn’t include the opening php tag in my code above, but trust me that there’s no whitespace before the opening php tag. The exit function after the redirect resolved this. I don’t think the redirect would work if there was any output, with or without the exit function. – John S Oct 16 '18 at 00:17
  • in my website exit() didn't work but also worked this: "" at the end of document. – Damianos17 Oct 17 '18 at 02:14