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...
Related
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.
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
I want to redirect from login page to my main page using php.
I use the following line of code: header('location:index.php');
inspite of redirection i received the error like:
Warning: Cannot modify header information -
headers already sent by (output started at C:\wamp\www\student\login.php:18)
in C:\wamp\www\student\login.php on line 19
This error occures if you print something before header() function.
For example:
<?php
echo 'test';
header('location:index.php');
exit;
?>
or even:
<html>
<head> .....
<?php
echo 'test';
header('location:index.php');
exit;
?>
You have to move this piece of PHP code before any operation that gives you an output.
You can also do the following trick but it is the second way you should try:
<?php
echo 'test';
ob_start();
flush();
header('location:index.php');
exit;
?>
you need to turn on the output buffer by inserting
ob_start();
at first line of php code
If you have already "echo'd" or "print'd" anything onto the page, either inside your script or outside of any set of PHP tags, then you cannot send any headers anymore. This is what your error message is stating.
Also, you should (try) to use full paths in location tags, it's better for SEO to use full URLs for every link on your website, let alone the redirects.
make sure that the header function is called before any response is outputted, e.g. header() function must be called before any echo functions or print_r, try removing the spaces before the <?php opening tag.
Its very difficult to decide what constitutes output to a page. I tried to eliminate my problem by removing all "echo's", "prints" etc but couldnt make the redirection work. I think there was a problem with a returned sql query. Adding the buffer and flushing it cured the problem.
You need to find out whether the header was sent already sent by checking line by line with header_sent() it will return true or false. If it's already sent you can't use header(). Try meta http-equiv="refresh" content="0;URL='your url'" /.Don't forget to add open and closing tags.<>
I have the code below:
<?php
session_start();
echo "\n\n";
echo "inputAction.php started";
//echo "<br/><br/>";
$name = $_POST["theUser"];
$passw = $_POST["thePassword"];
if (!strcmp($name, "myPassw") && !(strcmp($passw, "1234")) )
{
//echo "correct";
$_SESSION['sessionUser']=$name;
$_SESSION['sessionPassword']=$passw;
header("location:a.php");
}
else
{
//echo "wrong";
header("Location: index.php");
}
?>
My first attempt here is to echo "inputAction.php started"; after session_start();
However, I found out that I got an error:
inputAction.php started
Warning: Cannot modify header information - headers already sent by (output started at /Library/WebServer/Documents/01032011/inputAction.php:4) in /Library/WebServer/Documents/01032011/inputAction.php on line 16
But I notice that this will be fine if I comment out the echo after session_start();
<?php
session_start();
//echo "\n\n";
//echo "inputAction.php started";
//echo "<br/><br/>";
$name = $_POST["theUser"];
$passw = $_POST["thePassword"];
if (!strcmp($name, "myPassw") && !(strcmp($passw, "1234")) )
{
//echo "correct";
$_SESSION['sessionUser']=$name;
$_SESSION['sessionPassword']=$passw;
header("location:a.php");
}
else
{
//echo "wrong";
header("Location: index.php");
}
?>
What happened? Can somebody explain why echo makes the error?
Does that mean that it's a rule not to use echo after session_start?
Any other ways to print logs (alternative to echo) that I can use after session_start?
No, the rule is rather not to output anything before header. And if you take a closer look onto the error message, it says: “Cannot modify header information […] on line 16” because “output started at […]:4”.
The line where the output started does not need to be the first one with echo as PHP does also have an internal buffer that is not flushed with every echo call.
If you want to output something before header you need to buffer it using the output control. So just call ob_start before anything else and every output is buffered so that the HTTP header can be modified even if some output already happened:
<?php
ob_start();
session_start();
// …
That warning is produced with calling the header() function. The header() function sets HTTP header for the response you are sending back. And HTTP header must be the first thing in the response. No other output can be displayed before them.
There are many solutions to this problem. One is to turn on output buffering, which will magically take care of this. The better solution is to structure your code so that you don't output anything before any calls to the header() (or session_start() function). If you would use some MVC framework (cakephp, symphony, zend, ...) you wouldn't even have to worry about it.
This exact problem has been dealt here numerous times (it's one of the most popular questions about PHP). Look at this search results.
Also invest some time in reading PHP's error messages. The error message you provided clearly states that the error was "thrown" in the header() line, and which line started the output.
You've already sent information to the browser with the \n\n, so the browser constructed a page with default headers, as it will do if you send it any text at all (even a single character).
The browser's thinking, "OK, this is just plaintext, so I'll make it into HTML the best I know how and output it." As it does this, headers are made, and the document body is created, so any more headers you want to send it are ignored until this process is restarted (with a refresh).
For this not to happen, don't send any information to the browser until you're ready for it to start constructing the page.
Object buffering is an intermediate-difficulty topic that will take a while to get right if you haven't done it before.
Because you are using the header() function in your else statement, anytime your code goes in there, it tries to redirect your page. However, like Gumbo said, header() will throw an error if there is anything output to the browser before it is called.
If you want it to echo that and then redirect, so that the user can see it, you could do it with some good, old-fashioned HTML, and you would have control over how long it took to move to the next page.
session_start();
echo '<head><meta http-equiv="refresh" content="5;url=http://www.whatever.com/a.php"></head>';
echo "\n\n";
echo 'inputAction.php started';
etc.etc.etc.
But of course, you would still have to test the input to determine what url=, which means you'd either test twice or just put the echo in the ifs anyway. Of course, it doesn't matter where the initial echos are if using ob_start() because it will only be output when the script is finished running.
Also, you really shouldn't store passwords in the Session.
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");