PHP redirect header not working

I have my website hosted on 000webhost a year ago. Everything were working fine, however a 2 weeks ago I notice that the redirect header no longer working while it still working on XAMMP server.

I have this code to redirect the user once they logout to index page.
>

              	<?php
					session_unset();
    				session_destroy();
    				echo "<div class='centerMsg'>";
    				echo "<h2 class='green'> Thank you </h2>";
    				echo "<h3 class='green'>You will be redirected to the home page now</h3>";
    				echo "</div>";
     				header('Refresh: 2; URL=index.php');
				?>
            </div>

I have not changed anything. Why it is stop working?

Hi @kanyama.it!

Please try this one instead:

header('Refresh: 2; URL=index.php', true, 301);

In addition, move the header code before echo methods. Headers are first sent then the content.

1 Like

It still not working :sweat::expressionless:

Move the header before outputting the tags.

Like this:

              	<?php
					session_unset();
    				session_destroy();
                                header('Location: /index.php', true, 301);
    				echo "<div class='centerMsg'>";
    				echo "<h2 class='green'> Thank you </h2>";
    				echo "<h3 class='green'>You will be redirected to the home page now</h3>";
    				echo "</div>";
     				
				?>
            </div>

And I rectify my previous answer. Use this instead:

header('Location: /index.php', true, 301);

It not work. I tried it but nothing changed.

Please clear your browser cache and try again.

Also, what is the address of the webpage?

1 Like

Can you provide the exact URL where you are putting this code please.

I clear cache but not working. I tried different browsers.

The address : www.kanyamajdh.com

What file are you placing this code in? i.e. site.php or old.php or whatever

the file is logout.php

Problem solved. Please clear your browser cache and try again.

All headers must be sent before the actual content is delivered. If you want to do otherwise additional configuration from .htaccess is required and ob_start()/ob_end_flush() must be used as well.

1 Like

Thank you so much
But now it redirect the user directly I need it to take 1 or 2 seconds before redirecting them to the index

Then better use JavaScript for that.

Append this code before </body>:

<script>

setTimeout(function()
{ 
     window.location = "index.php"; 
}, 2000);

</script>

And remove header('Location: /index.php', true, 301); from begin of script.

Thank you so much
This was helpful.:smiley:

You’re welcome :blush: