How to declare more than one header on PHP - php

I want to send my users to different pages based on user action. So I made multiple functions at the top of the page like so:
<?php
function one() {
header("location: pagea.php");
}
function two() {
header("location: pageb.php");
}
function three() {
header("location: pagec.php");
}
?>
Of course I get an error because I am re declaring headers. At first I though it was going to be okay since I am containing them inside functions and am calling any one function at a time. But still I get the error. Is there any other way of doing this?

I think you misunderstand what the HTTP header Location does.
The Location header instructs the client to navigate to another page. You cannot send more the one Location header per page.
Also, PHP sends headers right before the first output. Once you output, you cannot specify any more headers (unless you are using Output Buffering).
If you specify the same header twice, by default, header() will replace the previous value with the latest one... For example:
<?php
header('Location: a.php');
header('Location: b.php');
header('Location: c.php');
will redirect the user to c.php, never once passing by a.php or b.php. You can override this behavior by passing a false value to the second parameter (called $replace):
<?php
header('X-Powered-By: MyFrameWork', false);
header('X-Powered-By: MyFrameWork Plugin', false);
The Location header can only be specified once. Sending multiple Location header will not redirect the users to the pages... It will probably confuse the crap out of the UA. Also, understand that the code continues to execute after sending a Location header. So follow that call to header() with an exit. Here is a proper redirect function:
function redirect($page) {
header('Location: ' . $page);
exit;
}

Either they aren't all in functions or more than one is being called.

Try something like this:
<?php
$page = // use an if statement or whatever you need to figure out
//which page you need (pagea.php, etc.)
fnx($page)
function fnx($page) {
header("location: " . $page);
}
?>
or
<?php
$page = // use an if statement or whatever you need to figure out
//which page you need (pagea.php, etc.)
header("location: " . $page);
?>

You're getting that error because your script has already produced output (you used echo/print before calling header()). You need to call header() before your script produces any output.
From the PHP Manual
http://php.net/manual/en/function.header.php
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'll get the following error when you attempt to call header() after sending any output...
Warning: Cannot modify header information - headers already sent

Here is how i like to do when i need to send multiple headers :
$headers = array(
'Location' => 'http://www.stackoverflow.com',
'Content-Type' => ' application/pdf',
);
foreach ($headers as $headerType => $headerValue)
{
header($headerType . ': ' . $headerValue);
}
Use headers_sent() to check if you'll be able to send headers or not.

function one() {
return "location: pagea.php";
}
function two() {
return "location: pageb.php";
}
function three() {
return "location: pagec.php";
}
header(one()); // for example
Maybe something like that?

For the sake of people who may be coming here from Google, if you're interested in having multiple of the same type of header:
It is technically possible to have multiple headers that are of the same type passed in PHP. header has a parameter called "replace". From the documentation:
The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type.
So you should be able to write:
header("location: pagea.php"); #You want to overwrite the initial one, so you'd have this one be default, or true
header("location: pageb.php",false);
header("location: pagec.php",false);
Of course, if your type of header can't be had multiple times, you'll get an error. In this case you get this error (written this way in Chrome):
This page isn’t working
localhost sent an invalid response.
ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION
For other headers, however, this method should work fine. The example they supply is:
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);

I have a nice solution:
die(header("Location: someting.php"));
You can do that as often as you want.
(Nothing else worked for me and to me this is a nice alternative).
Especially for everyone who has a problem with using multiple options for "header" (on my site it would always just take one, no matter what I did).

You can try something like that.
<?php
function one() {
$redirect=pagea.".".php;
}
function two() {
$redirect=pageb.".".php;
}
function three() {
$redirect=pagec.".".php;
}
header("location:".$redirect);
?>

Related

How can I send a user to another url without a header redirect?

I'm learning PHP and been looking for this for a while. What I want to achieve is something like so:
if (true/false) {
go to this url;
}
Every time I search terms like php redirects or php links etc., 99% of the time I get something "headers". I read that header redirects can achieve this but no code can go before it, that it must be first on the page else it wont work.
If that's so, then how can I achieve this?
i read that header redirects can achieve this but no code can go before it. that it must be first on the page else it wont work.
That's wrong. There must be no output before this. Thus you have to ensure, that you don't echo, print, ?>something<?php (or whatever) anything before.
if (true) {
header('Location: ' . $url, false, 302);
exit; // Ensures, that there is no code _after_ the redirect executed
}
You can ready everything about it in the official manual. Especially:
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.
echo '<script type="text/javascript"> document.location = "http://yoururl.com";</script>'
and this will be executed when this part of script is executed.
You can use this if you need some output before the redirect:
header("refresh: $time_in_seconds; url=$your_url);
You still must call this before output is actually sent however. Send the header, then send your output - the page will "redirect" in the time specified.
Disclaimer: I must admit, I'm not sure what the implications of this are and can't find docs on it, so I can't necessarily recommend it - but I can validate that it works.

How to redirect a person after loggin

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

PHP - header("Location:") inside a function redirects without calling function

I'm using a function called headerLocation() in order to redirect properly.
This is the pertinent part of the function, I'm using it to redirect and then display an appropriate message (personal preference).
function headerLocation($location,$message)
{
$_SESSION['output'] = $message;
header("Location: ". $location);
}
The problem is, when I run the script, the header("Location: ". $location); part is activated without even calling the function (when I initially require it for php parsing).
This renders the function useless.
Is there any way around this?
In addition to the feedback already given. It is a good idea to exit after you redirect.
function headerLocation($location,$message)
{
$_SESSION['output'] = $message;
header("Location: ". $location);
exit;
}
That should not happen. Either you are calling the function somewhere, or another part of the code is writing out the header. Can you add some debug to that function to check?
Just a guess, perhaps you should buffer your output ( ob_start() )
This will cause headers to be sent only when the output is flushed, allowing the rest of your code to execute.
It makes no sense for the header() function to redirect without calling headerLocation() first.
My guess is that you're not seeing $_SESSION['output'] hold $message, and that makes you think the function is not being executed. Try writing to a new file instead, does that work? I bet it will.
The reason $_SESSION might not be holding your values is probably because of P3P and your browser and / or PHP configuration.
Also, are you sure you don't wanna call die() / exit() after the header() redirect?
The redirect happens too fast for the $_Session to be written properly. Use
session_write_close();
before the header call.
Edit: Removed the ridiculous $ in front of the function call.

PHP page redirect [duplicate]

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");

How can I redirect in PHP without header errors?

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.

Categories