header function [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I have a PHP file which I'm using to check username and password. This part is working, but after successful login I would like to use header() to redirect to user panel page. This is the logged error that I'm getting:
[10-Dec-2012 12:25:26] PHP Warning: Cannot modify header information - headers already sent by (output started at /home2/jzperson/public_html/imes/php/login.php:10) in /home2/jzperson/public_html/imes/php/login.php on line 32
This is line 10:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
And this is line 32:
header("Location: http://imes.jzpersonal.com/userpanel.html");
Any idea why?

You probably have some output echoed out before getting to the line 32 with your header call.
See description of the header function: 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.
Clarifications
To clarify things a little bit, the redirection using header() is performed by including a raw location response-header field to the server response. When the receiving party reads the response and sees that header field, it drops the current response and issues another request to the destination you provided.
Now, headers always come at the top (head) of the server response. That's why they are called headers! If you output any content, PHP will immediately "prefix" it with default headers and it's not possible to add any more of them after this point. So, by attempting to set another header later in your code, you get an error:
Cannot modify header information - headers already sent
By outputting HTML at line 10 you can no longer issue any more headers, because they were already sent (prefixed to your HTML output).
You can find more information about headers here: http://www.faqs.org/rfcs/rfc2616.html

Basically, you need to check whether the user is logged in or not (and redirect) before anything is sent to the browser (before HTML). Your code, then, would look something like this:
<?php
...
if($loggedIn)
{
header("Location: http://imes.jzpersonal.com/userpanel.html");
exit();
}
?>
<html>
...
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

You are trying to write something before header statement
Remove any echo statements/html content before header statement. That should do the trick

You could also cheat and just use output buffering - at the very beginning of the script tree use ob_start(); to begin capturing the output. You can use headers and set cookies etc as much as you like then.
At the last line of the script tree use ob_end_flush(); to send the output. You can also grab it to a variable to further process if you wish with $buffer = ob_get_clean();
Although its not a solution as such it does allow for a more flexible coding environment AND it will solve your above problem.
Its best to flush and die if you are going to be sending a Location header:
ob_start();
/* very long snip */
header('Location: somepage.php');
ob_end_flush();
die();
This will prevent any further processing after the location change has been sent.
Just as a side note: When I speak of a script tree I mean the include path - like put the ob_start(); into a header file thats included before anything else and a footer file that flushes (and processes if required) the output buffer. Remembering, as highlighted above, that Location changes should have the script halted immediately after.
Sessions may also need to be closed with a header Location followed by a die - to use that simply
ob_start();
/* very long snip */
header('Location: somepage.php');
ob_end_flush();
session_write_close();
die();
I found that one out after hours of wondering why session data was being lost! Bear that on mind.

You can't use header(); if anything has already been sent as output. This means HTML. Do all your PHP processing first, then output your HTML/JS.

Related

Header function not working for the log out and log in

Well I have have already read the cannot modify header
But still I'm getting the error
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\xampp\web\librarian_menu.php:582)
This is my code , I don't know what i am doing wrong
<body>
<?php
#session_start();
require 'connect.php';
if(isset($_SESSION['lib']))
{
echo '<strong style="position:relative;top:25px; left:940px;">'.$_SESSION['lib'].'</strong>';
}
else
{
echo "<script>alert('You need to login first')</script>";
header('Location: quote.php');
}
if(isset($_POST['log_out']))
{
unset($_SESSION['lib']);
header('Location: quote.php');
}
?>
.
.
.
If what you posted above really is your code, then it is pretty obvious where the problem comes from. Just look at the first line of code right before your opening php tag:
<body>
<?php
#session_start();
require 'connect.php';
See the <body> tag? You output it before anything else. A similar issue exists within the else branch of the first conditional: first you echo some string, then you call the header() function. You simply must not output / echo anything prior to calling that header() function.
Note that such code might work, when the http server caches the preliminary output. But you have no guarantee for that. So you cannot rely on it. Apparently in your case that output is not cached, but sent before you cann the header() function.
The reason for this behaviour of php, for this issue is a simple one: http headers are preceding an http reply. Per definition there cannot be any content contained in a reply before the headers. So once php start to send any content it must close the headers and sent them first. If you try to add any additional headers afterwards php has no choice but to raise an error: sending simply is impossible within that reply.
You have to restructure your code to sent the headers prior to anything else. If that really is not possible, then you might want to take a look at "output buffering". It allows you to hold back any output and release it to the client only later, after having done whatever is required, for example defining additional http headers.
Any maybe a side note, just to make things crystal clear: with the message "Warning: Cannot modify header information..." php refers to the http headers, not to any html header tag you might use.
Before header function (such as session_start, header) you cannot output anything to the browser - remove echos and html tags like <body> from the code before session_start() or header().
Read the first few lines of this : http://php.net/manual/en/function.header.php

Redirecting using header after updating database [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I need help with redirecting using header.
My code:
<?php
if($fname != "") {
$query = mysql_query("UPDATE customer_address SET first_name='$fname',last_name='$lname',company='$company',company_id='$company_id',
address_1='$address_1',address_2='$address_2',city='$city',county='$county', post_code='$postcode',country='$country'
WHERE address_id='$editThisId';");
if($query==true) {
header('Location: address.php');
} else {
echo "Update Error!";
}
}
And I get the following error:
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\eula\edit-address.php:72) in C:\xampp\htdocs\eula\edit-address.php on line 129
Pastebin for whole file: http://pastebin.com/vj2Mp7u0
Thanks in advance!
You are getting this error because your server already sent information to the client's browser - Headers need to be sent first before any HTML is transferred.
Simply put the code which is supposed to redirect the user at the very top of your file before any HTML or echo-calls.
Alternatively, you can call ob_start() at the top of your file to disable output buffering and send the page as a whole after every bit of your PHP code has executed.
You can not have any html content being displayed before the header, example:
<html>
...
<?php
// your code
header('Location: address.php');
?>
Try putting the php code, before any html content.
"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."
from
http://www.php.net/manual/en/function.header.php
You could also try moving your php to the top of the page (before any of the HTML) instead of the bottom. That way the php would look for if(isset($_POST['submit'])) before anything on the page is rendered.
Your redirects should work then I think.

PHP: Header wont redirect [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
When i put my website online, all of the headers will not work. But when i built it, just on a local database etc. it worked "Works" fine.
I get this ERROR on the website currently:
Warning: Cannot modify header information - headers already sent by (output started at /customers/5/8/4/infuze.dk/httpd.www/index.php:22) in /customers/5/8/4/infuze.dk/httpd.www/includes/functions.php on line 16
I used my google foo a little and as far as i can understand is that i cant output any data before i use headers. But i dont thing that is the case here.
Here is the code i used in on the site.
if(empty($_GET['page'])){
header('location: index.php?page=homepage');
}
or at least one example
I usually get the error "Cannot modify header information - headers already sent by" when the page you're trying to redirect from contains information. Check to see if the script uses echo, include, require, etc., or contains HTML markup before the line at which you try to redirect.
<p>Hello!</p>
<?php
header('location: index.php?page=homepage');
?>
Will NOT work, because it sends the browser information before trying to redirect.
<?php
echo "Hi!";
header('location: index.php?page=homepage');
?>
Also won't work, because it also sends the browser information before trying to redirect.
<?php
header('location: index.php?page=homepage');
include('setup.txt');
?>
<h1>Amazing page!</h1>
WILL work, because it tries to send the browser information AFTER the redirect, but not before.
Headers won't redirect in the following conditions:
Any blank space is remaining in the file after ?> tag.
To avoid this, please avoid ending ?> tag (file end).
Please check whether, any echo or print statement is written accidentally.
Also, please check whether any HTML tag is remaining there.
If you follow, all this, your script will work.
Finally, in the starting of the file, put
ob_start()
This function will store all your page's output in a buffer and thus your redirection will work.
Try this;
<?php
ob_start();
// code
ob_end_flush();
?>
>> Call ob_start() at start of the script.
>> call ob_end_flush() at the end of script.
Thanks!

Can i change header redirect in php to javascript redirect with same status in PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
My site is http://www.seoitc.com, we are using joomla for this site, but have 1 problem when i try auto redirect to anypage that show error: Warning: Cannot modify header information - headers already sent by ().
I tried change redirect to use js but cant use same status(302,303...) same as in php. Please help to fix this problem please.
Thanks!
Any output is being sent before you call your header function. Check for any html code before your header call, even a white space or a blank line will cause that
According to PHP Manual
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 use ob_start() at the top of the page. to prevent error.
but also you can use this code. if any error happens in your page it will redirect you to the $page:
// page address
function redirect($page)
{
header("Location: ".$page);
}
set_error_handler("redirect");
And you can check this out: Headers already sent by PHP

PHP: Redirect ( header)

header("profil.php?id=" . $show["id"]);
What i tried to do, but headers are already sent at top, so how can I redirect the user? Should I use window.location.replace("URL"); (javascript) instead?
If you can't control the very beginning of the script, where headers would be sent, then yes, your only method is to use JavaScript.
Also, the proper syntax is header('Location: profil.php?id=' . $show['id']);
You need the Location: part so the browser knows what header it's receiving. Also, don't forget to do an exit() or die() right after the redirect.
Someone correct me if i'm wrong, but I think you can use ob_start() at the beginning of your page and that will allow you to redirect via PHP even if headers are already sent.
You should redesign your application, to make it more sensible.
It should start output only when it necessary, not just every time this file is called.
You have to modify all your code by dividing every script to 2 parts. First part will contain all data manipulations and second will contain output only. It will be better to put the latter one into separate file, called template. thus your profiles php will looks like
include 'dbc.php';
//some code that sends headers, gets data etc
//after it's all done, call your template files
include 'top.php';
include 'profiles.tpl.php';
include 'bottom.php';
there can be some variations, but the main idea would be the same: separate your data manipulation from data presentation.
From the header 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.
The headers are being sent before your call to header() due to output from the script. You just need to track down where the output is coming from.
I see it that you have two options
1) You try to ensure that your headers are not set until after you have executed your code. Your headers being set before you have even determined what you are sending back to the user suggests your code is a little messy, or you are constrained in some way.
2) You can use your javascript solution. However, I would consider this as a hack, rather than an appropriate solution. Try to figure out the answer to why you can't use approach 1.
EDIT: A code example added
Your code should look something like this
<?php
// perform logic to determine if you need to do the redirect or not.
// if you do need to redirect, set the following
$iNeedToRedirect = true;
// if you do not need to redirect, set the following
$iNeedToRedirect = false;
if ($iNeedToRedirect) {
header("Location: profil.php?id=" . $show["id"]");
die();
}
// if code gets here, carry on as normal
include("dbc.php");
include("top.php");
... etc etc etc
?>

Categories