This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 5 years ago.
Can PHP make a redirect call after executing a function? I am creating a function on the completion of which I want it to redirect to a file located in the same root folder. Can it be done?
if (...) {
// I am using echo here.
} else if ($_SESSION['qnum'] > 10) {
session_destroy();
echo "Some error occured.";
// Redirect to "user.php".
}
Yes, you would use the header function.
/* Redirect browser */
header("Location: http://www.yourwebsite.com/user.php");
exit();
It is a good practice to call exit() right after it so that code below it does not get executed.
Also, from the documentation:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
This means you should not echo anything right before the header() function, as doing so will more than likely throw an error. Also, you will need to verify that this code gets run before any other output as well.
Using a javascript as a failsafe will ensure the user is redirected (even if the headers have already been sent). Here you go:
// $url should be an absolute url
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location=\''.$url.'\';</script>');
}else{
header('Location: ' . $url);
die();
}
}
If you need to properly handle relative paths, I've written a function for that (but that's outside the scope of the question).
Simple way is to use:
echo '<script>window.location.href = "the-target-page.php";</script>';
$url='the/url/you/want/to/go';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
this works for me fine.
header( "Location: http://www.domain.com/user.php" );
But you can't first do an echo, and then redirect.
<?php
http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);
?>
As metioned by nixxx adding ob_start() before adding any php code will prevent the headers already sent error.
It worked for me
The code below also works. But it first loads the page and then redirects when I use it.
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';
You can use this code to redirect in php
<?php
/* Redirect browser */
header("Location: http://example.com/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
Yes.
In essence, as long as nothing is output, you can do whatever you want (kill a session, remove user cookies, calculate Pi to 'n' digits, etc.) prior to issuing a location header.
if you want to include the redirect in your php file without necessarily having it at the top, you can activate output buffering at the top, then call redirect from anywhere within the page. Example;
<?php
ob_start(); //first line
... do some work here
... do some more
header("Location: http://www.yourwebsite.com/user.php");
exit();
... do some work here
... do some more
The header() function does this:
header("Location: user.php");
Related
(I'm new here so forgive me if this question is dumb)
Hello i'm looking for a solution to redirect to another page after a certain function is called. For example
if (condition is true) {
redirect ()}
function redirect() {
redirect
}
I can't use the header function here because
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
Is there any way to do this?
This also works:
if () {
echo "<meta http-equiv='refresh' content='0;pagehere.php' />";
exit();
}
If you want to make absolutely sure that the user gets redirected, I think letting PHP handle the redirect is the best approach. This means that you either have to make sure that no HTML/spaces are outputted first (preferred), or use output buffering control with the ob_start() function at the beginning of your script.
Documentation: http://php.net/manual/en/function.ob-start.php
Then you can use a PHP redirect just fine.
header("Location: http://www.example.com/");
exit;
You can write javascript with php that will be interpreted as soon as it is read by the browser..:
<?
if(...)
{
echo '<script type="text/javascript">window.location.href = "http://stackoverflow.com";</script>';
}
?>
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.
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.
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. :-)
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();
}
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();
?>
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.
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.
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.
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
}
Try adding
ob_start();
at the top of the code i.e. before the include statement.
Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.
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.
Try this, Add #ob_start() function in top of the page,
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
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();
}
?>
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');
...
Many thanks in advance for even attempting to present a solution.
I'm having trouble with a simple html contact form.
The form's method is set to post and it's action is sent to a php file.
At the end of the PHP file the form is sent to, there is a basic location:redirection.
ex) header("Location: ../index.htm");
I configured my php.ini file (Apache) to display the php error(s).
This is what I'm shown:
"Cannot modify header information - headers already sent by (output started at /home2/jwarddes/public_html/newTest/php/contact.php:2) in /home2/jwarddes/public_html/newTest/php/contact.php on line 20"
Line 20 of my code is my header("location:... redirect. This appears to be fine, yet something keeps throwing an error.
Needless to say, I'm stumped.
Could someone please try their hand at a solution or kindly nudge me in the right direction?
Thanks!
I have had this problem many times before, I've seen solutions here and there which haven't worked. In my case I have put it down to the fact that I (php include) my pages into an index, which already has a header attribute.
The way I have worked around this is to use the meta method, echo '<meta http-equiv="refresh" content="0;url=<URL>" />';
To make your page look a little better, you can add a one or two second delay and do something like...
if ($ = $) { echo '(H1)Redirecting you to...(/H1)'; echo '<meta http-equiv="refresh" content="1;url=<URL>" />'; }
that is a common problem.
make sure you do not have any output (even a simple space at the top of the page) as that will send the headers prior to your redirect.
Possible Solutions are the following.
ob_start();
in the top of your page and
ob_end_flush();
at the bottom might solve your issue.
Also, I have this special function below which do a very smart redirect, try it out and let me know :)
/**
* redirect()
*
* Attempts to redirect the user to another page.
* It tries to PHP header redirect, then JavaScript redirect, then try http redirect.
* The following redirection method is only attempted if the previous redirection method attempt has failed
*
* #param mixed $url To be redirected to
* #return nothing
*/
function redirect($url)
{
if (!headers_sent())
{ //If headers not sent yet... then do php redirect
header('Location: ' . $url);
exit;
} else
{ //If headers are sent... do java redirect... if java disabled, do html redirect.
echo '<script type="text/javascript">';
echo 'window.location.href="' . $url . '";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
echo '</noscript>';
exit;
}
} //==== End -- Redirect
There should not be any output (echo) send to browser before this line:
header("Location: ../index.htm");
Post your code, so that I can find out the exact issue
From the manual:
PHP header()
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
You can't have anything printed out to the browser before using the redirect.
Anyway if you really want to do that you can do such trick:
echo "<script>location.href='...';</script>"
But that's not recommended as whatever you print out before you redirect cannot be seen by the user so why bother letting it out?
its most probably because of a space at the starting or ending tag of
check that I had the very similar problems when working on...
I'm using the below function to redirect a person after specific task (eg.: after login, after logout, after searching etc.)
code is below:
<?php
class common {
/* Redirect to another page
* $url= Url to go
*/
function redirection($url){
header("location: $url");
exit();
}
// Some other function below
?>
But now I'm dealing this class with many project of different host (MLM project). I have a problem now. With some server it works as i expected, but in some other server, it's not redirecting. If i enable error_reporting(E_ALL); i found a notice that headers are already send. So I'm in confusion that what can I do now instead of header() function. Also i tried the below code
<?php
function redirection($url){
echo "<div align='center'><a href='$url' target='_top'><img src='../img/proceed.jpg' alt='Proceed>>' align='absmiddle' border='0'></a></div>";
exit();
}
?>
But it is not desirable as everybody wants automatic redirection. My servers are windows and linux both. Please help me anyone
well, this situation is very common, then you can simple turn on output buffering (the output will be stored in an internal buffer).
Use ob_start(); in the very first line of your application
<?php
class common {
/* Redirect to another page
* $url= Url to go
*/
function redirection($url)
{
header("location: $url");
exit();
}
// Some other function below
}
?>
<?php
ob_start("redirection");
// Your Common Class Page
include("Common.php");
// some code
ob_end_flush(); // turn off output buffering
?>
One way to deal with this is to test if the header has already been sent before calling header(location). You could use mix both solutions:
<?php
class common {
/* Redirect to another page
* $url= Url to go
*/
function redirection($url){
if (!headers_sent()) {
header("location: $url");
} else {
echo "<div align='center'><a href='$url' target='_top'><img src='../img/proceed.jpg' alt='Proceed>>' align='absmiddle' border='0'></a></div>";
}
exit();
}
// Some other function below
?>
This way if the headers haven't been sent, you redirect automatically. If they have, you ask the client to click.
This is the reason why when you see a redirection notice in most websites, it also includes a sentence stating - if you are not redirected automatically, please click here...
Hope this helps.
Good luck!
If headers have already been sent, it is likely because content has already been written out to the screen (via an echo, print, or similar). Since your class has no control over what came before it was instantiated and the function was called, it seems unlikely that you can do much to avoid your client PHP (what calls your class) from writing anything out before. Either use Javascript or use Apache redirects.
I would try using:
header("Location: ".$url, TRUE, 302);
If you want to use a different method, or called "refresh" method,
header("Refresh:0;url=".$url);
Both would work in every case. The problem with your header is, you need to let them know it's a 302 redirect, as well as set TRUE to replace the existing headers. If header is already set, you need to replace it using TRUE boolean.
302 is also the common HTTP response code for redirection, which needs to be specified when you are trying to redirect using header.
The Refresh method works fine as well, though it has compatibility issues with older browsers.
http://en.wikipedia.org/wiki/HTTP_302
http://php.net/manual/en/function.header.php
the easiest way is to do it through client side. javascript...
window.location= url
How can I redirect in PHP with this setup below without getting header output errors, I understand that nothing can be printed to the browser before a header is set, I am looking for a solution, not an explanation of why it happens please.
<?PHP
// include header
include ('header.inc.php');
// In my body section file if this is a page that requires a user be logged in then
// I run a function validlogin($url-of-page-we-are-on); inside of that file
//the function is below, it outputs a redirect to login page if not logged in
// include body of page we want
include ('SOME-FILE-HERE.php');
// include footer
include ('footer.inc.php');
// here is the function that is in the body pages, it is only called on a page that we require a logged in user so there are hundreds of pages that do have this and a bunch that don't, it's on a page to page basis
function validlogin($url) {
if ($_SESSION['auto_id'] == '') {
$msg = 'Please login';
$_SESSION['sess_login_msg'] = $msg;
$_SESSION['backurl'] = $url;
$temp = '';
header("Location: /");
exit();
}
}
?>
I would like to user php's header function and not a meta or javascript redirect
Also maintainning a list of pages that require login or not is not an option here if possible
Use ob_start() in the first line even befor the include. so you can set headers anytime.
Can't you just do this:
<?php
validlogin($url); // call the function here
include ('header.inc.php');
include ('SOME-FILE-HERE.php');
include ('footer.inc.php');
?>
Or, put the include files in every one of the "SOME-FILE-HERE"-type files, if that's possible, so you end up with:
<?php
validlogin($url); // call the function here
include ('header.inc.php');
?>
<h1>Page heading</h1>
...page content etc...
<?php
include ('footer.inc.php');
?>
use { echo '<META HTTP-EQUIV="Refresh" Content="0; URL=process.php">';}
As long as you have no script output before the header() function you should be fine. Check there are no echo's or whitespace. Also putting ob_start() at the beginning can help. sometimes there is invisible whitespace - changing the format of your document to ANSI or Unicode may help!
As a note (although I think you already know) header does not terminate the script so the exit() (which you have) is a definite requirement.
Does the footer.inc.php and SOME-FILE-HERE.php write to the response stream immediately? Because if so, this won't work as you will have already written something before you sent the headers.
You need to buffer the ouput so that the HTTP header is not send on the first output. You can either buffer any ouput implicitly by enabling ouput_buffering or explicitly by calling ob_start. But the latter has to be called before the first output, so ideally in the first line of the script that’s initially called.
As already mentioned by the others use ob_start() or the output_buffer-setting to buffer the output. Apart from that it's from my point of view not a good practice to output content in the middle of functional code but this is a another topic.
You can find more information at Google or in this Article about Output Buffering in PHP.