problem with setcookie - php

there is one think, i can't understand anyway:(((
when i try to set cookie(it is on line 28 in login.php), browser returns me an error!!!
Cannot modify header information - headers already sent by (output started at C:\xampp2\htdocs\video\index.php:9) in C:\xampp2\htdocs\video\login.php on line 28
but on line 9 in index php, i haven't any header!!! there is a tag!!!
i cant understand it!!! can somebody tall me why it returns me such error?

Cookies are sent as headers. From the PHP docs for setcookie:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
Also, if your page is saved in UTF-8 format, the BOM (Byte Order Mark) will stop you from being able to set any headers, as it counts as output. See http://bugs.php.net/bug.php?id=22108. To get around this you need to save your file without the byte order mark.
See also: Byte order mark#Unwanted BOMs - Wikipedia

You can't print out anything on the site before sending a Header.

set the cookie first before any html tags (a.k.a output), even before declaring !DOCTYPE html or head, header information and the like. for example your file could look something like:
<?php setcookie("oreo", $value, time()+(60*60*24*30));?>
<?php setcookie("vanilla_wafer", $wafer, time()+(60*60*24*30));?>
<!DOCTYPE html>
<head>
<title>Cookies and Milk</title>
</head>
<body>
<p>yo</p>
</body>
</html>

Please post some code.
What this error means is, that something was already sent (can also be an echo, error notice etc.).

You have to have your header functions at the very top of your application. Like basically the first lines are for header();

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

session_start() throwing error

I am currently getting the following error using php:
Warning: session_start() [function.session-start]:
Cannot send session cache limiter - headers already sent
(output started at /home/paramireze/madisonh3.com/calendar.php:1)
in /home/paramireze/madisonh3.com/includes/common.php on line 5
The first line of every file is include common.php, and the first line of code in common.php is 'if(!isset($_SESSION)) {session_start();}`.
This error only occurs on calendar.php and news.php (you can see the error if you visit http://www.madisonh3.com/calendar.php). All my files are the same, which includes a common.php. After that, I will write the html tag and include the header from there.
I've read other discussions regarding session_start and all say to make sure you do not output any html before session_start. Also, if I am doing something wrong, why is it only happening to two out of my 10 files?
There is something outputting data BEFORE your session_start() command. As the session cookie is set to the HTTP header it must precede any HTML output.
The error Cannot send session cookie - headers already sent by (output started at /home/paramireze/madisonh3.com/calendar.php:1) in /home/paramireze/madisonh3.com/includes/common.php on line 5 indicates something is outputted before.
So look into your code and find what could be echoing data before your session_start().
You should care that your editor does not store the utf-8 BOM header, this header is sometimes stored at the begin of the file with 3 bytes .
The editor will hide them, so if you are not sure if your file contains these characters, you can either use a non interpreting editor (hex editor), or this wonderful online W3C checker. The BOM header is treated as output by PHP, and this can cause nasty Cannot modify header information - headers already sent errors.
Checking your URL shows, that there is indeed such a BOM header. Have a look at the settings of your editor (IDE).

header function [duplicate]

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.

Can't redirect to another page at the end of the PHP script

Bot of these lines:
echo '<br/><br/>'.$_SERVER["SCRIPT_NAME"]."?page=".$pager->GetVariableC."&threadID=".$threadID;
header("Location:".$_SERVER["SCRIPT_NAME"]."?page=".$pager->GetVariableC."&threadID=".$threadID);
Give me this:
/PoliticalForum/Thread/thread.php?page=2&threadID=6
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\PoliticalForum\Thread\comments.php:42) in C:\xampp\htdocs\PoliticalForum\Thread\thread.php on line 348
How do I redirect at the end of the script?
When this error happens, you have already sent something to the browser, by using echo or by having a couple of new lines after the closing php tag. Be sure not to have any new lines or echoing something before redirecting.
You can't redirect after you've sent output to the client's browser using PHP's header().
What you can do is use a meta tag:
<meta http-equiv="refresh" content="2;url=http://www.destination.com/">
Where 2 is the time before the redirect in seconds, and the url is the destination. You can find more information about it here (you should read the drawbacks section).
You can't redirect after you've already sent any data to the browser, in this case the first line is doing so. Why are you trying to print something that you are never going to see (The browser would be immediately redirected)?
Either remove the outputting lines above the redirect if possible, or look into using output buffers if you can't modify the surrounding code.
If you want output and a redirection then you need to use a javascript redirection. http://www.tizag.com/javascriptT/javascriptredirect.php
What you're doing here is called an HTTP redirection (an HTTP 302), which is one of the HTTP headers sent to the browser as a response.
This error message is due to the fact that you echo'd content which has the effect of sending out all the buffered HTTP headers then tried to set a header (but it was already sent). To get a much better view of this I recommend all web developers install firebug and monitor the "Network" tab, you'll really get a better grasp on headers and their meanings.
Cheers

what means by top of the page in php file

i read somewhere that ob_start() should be places top of the page. whereas
somewhere i read that session_start() should be placed on the top of the page.
somewhere i read header() should be placed on the top of the page.
somewhere i read include() or require() should be placed on the top of the page.
i m getting confused what should be written on the top and in which order ther are placed ? and what means by on the top??? is it
before <html> or
after <html> or before <head> or
after <head>
please tell me what is real order of all these function
like same manner where we have to put ob_end_flush(); and other function, at the bottom of the page after <html> or after </body> and what is the order of functions that comes on the bottom of the page
In order to understand the value of the statements you have written you need to have some basic understanding of the operations of the functions you mention. I'll try to break them down here.
Let's start with session_start() and header() calls:
The first function does exactly what the name implies; it starts a session.
Due to the stateless nature of the HTTP protocol, there is a need for some mechanism that can remember state between page requests. This can be achieved with sessions. Although sessions, in the early days of PHP where sometimes propagated by passing along the session ID in links ( someurl?sessionId=someSessionHash ), this, nowadays, is considered bad practice.
Nowadays, sessions are predominantly kept track of by using a cookie (in the early days they where widely used too, don't get me wrong). This session cookie (which, contrary to popular belief, is nothing more than a normal cookie, with merely the session ID in it, that (usualy) simply expires after you close your browser) is sent along to the browser with each subsequent page request. And here is where the catch is: A cookie is sent as a header of the response (meaning before the actual body), like so:
// I've left out a lot of other headers for brevity
HTTP/1.x 200 OK
Date: Sun, 31 Jan 2010 09:37:35 GMT
Cookie: SESSION=DRwHHwAAACpes38Ql6LlhGr2t70df // here is your Cookie header
// after all response headers come the actual content:
// the response body, for instance:
<html>
<head>
</head>
<body>
</body>
</html>
Now, because response headers must be sent before the response body, you need to put a call to session_start() and header() before any body content is output. Here's why: if you output any response body content (could be something as simple as a whitespace character) before a call to session_start() or header(), PHP will automatically output the response headers. This is because a HTTP response must have the response headers sent out first before the response body. And it is exactly this that often leads to the infamous Warning: headers already sent warning in PHP. In other words; once PHP has sent out the headers, because it had to send body data too, it cannot add any headers anymore.
So, now that you understand this about the HTTP protocol, there are some measurements you can take to prevent this from happening. And this is where we come to the next function(s):
ob_start, ob_flush, etc...:
In a default setup PHP usualy outputs anything immediately. Therefor, if you output any response body content, headers are automatically sent first.
But PHP offers mechanisms of buffering output. This is the ob_* family of functions. With ob_start you tell PHP to start buffering. And with ob_flush you tell PHP to flush the buffer; in other words output the current content of the buffer to the standard output.
With these buffering mechanisms you can still add headers to the response, after you have output body data, because you haven't actually sent body data yet, you have simply buffered it, to be output later with a call to ob_flush or ob_end_flush and what have you.
Keep in mind though, that using ob_* functions is more than often a code smell. In other words (and this is why it is important to do certain stuff at the top), it is then used to make up for poor design. Somebody forgot to set up their order of operations properly and resorts to output buffering to circumvent this header and session drama.
Having said all this, you can easily see why the outputting of html and/or other body content should come last. Apart from that, I strongly recommend you to separate PHP code from output code anyway. Because it is much more easy to read and understand. And a good way to start doing that is having the actual html come after the main <?php ?> code block. But there are other ways as well, which is beyond this questions scope.
Then lastly about the include and require calls. To have these at the top of your php files is usually ment to be clarifying. It keeps these calls nicely in one place. But keep in mind, that if one of these files output anything before you call session_start() or header() without using output buffering, you're screwed again.
"Top of the page" means before any output. "Bottom of the page" means after all output.
It simply means before any other character, where "other" means "non PHP code".
All code between <?php and ?> is not sent to the browser, so it doesn't count. Thus usually "top of the page" means before the <html> start tag. Be careful because if you have an empty line or even just one single whitespace before that tag (or even before the PHP opening tag), that counts as output.

Categories