Is it possible to prevent headers to send again? - php

imagine this:
<?php
include_once('galeria.php');
?>
the galeria.php file is a complete html/php file.
Is it possible to include the file and prevent headers to send again?
I just don't want to use iframe or change my include files.

You have confused everyone by using the term "headers". Headers is what is sent by the web server to tell the browser what to do with the payload. You are talking about the HEAD and I suspect HTML and BODY tags.
Well any sensible person would simply split the files up into section, but for some strange reason (you haven't told us why) you state that you do not wish to do this. In that case you can read in the galeria.php file and use either PHP's DOM class methods (preferred) or some REGEX (less good) to extract the body payload from the galeria.php file.
Can you tell us why you do not want to design this sensibly?

Headers are sent only once - right before the first bytes are sent to the browser. The bytes can be sent to the browser by (for example) echo(), print(), or by literal text/html outside the <?php ?> sections.
If your file which is including the galeria.php does not need to send any headers explicitely, then you have nothing to worry about.
Otherwise - if your file which is including the galeria.php needs to send headers explicitely, you may buffer the output of galeria.php as follows:
First, call ob_start() (redirects all the output to a temporary buffer),
Then include galeria.php (output gets sent to the buffer, not to browser. Headers are not sent yet),
Then send the headers as you need via header(),
Call ob_end_flush() to send the buffer contents to the browser (and all the default headers with it).
See http://www.php.net/manual/en/function.ob-start.php and http://php.net/manual/en/book.outcontrol.php

include_once
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
Official Document

Related

Call header() after output is sent

According to the PHP documentation:
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.
but when I tried the example that the documentation reports (with a little change):
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('X-Header: http://www.example.com/');
exit;
?>
all worked just fine, no error poped up and I smoothly got my <html> tag in the output and my X-Header in the headers.
I'm using PHP 7.1.9, so is still correct what the documentation says?
The documentation is still correct.
For performance purposes, the interpreter puts the output in a buffer. When the buffer is filled for the first time, the interpreter sends the headers then it sends the content of the buffer (and empties the buffer). After this point any call of the function header() fails. The headers cannot be modified any more and other headers cannot be added because the headers have already been sent.
This lets the script produce a small amount of output before sending the headers.
Read more about output buffering configuration settings.
The option output_buffering allows turning the feature off or on and even setting the size of the buffer.
The option implicit_flush tells the interpreter to flush the buffer after every output block. This forces your script to send the headers correctly, before any output.
edit your php.ini and enable Output Buffering ..

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.

Setting PHP headers within function / class method

I have written a class which outputs content type information as a header, however this does not work. After reading PHP.net it states
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.
I am unsure what to do as I cannot hard code the content type everywhere needed. Does anyone know if it is possible to set headers in functions / classes at all?
The restriction is that the headers must be sent before any other output is sent.
The easiest solution would be to enable output buffering. So you can set headers anywhere till the buffer is flushed.
You can do this ether by using the function ob_start
Or using the output_buffering ini directive in php.ini file.
As pointed out by Brad, it is not the most efficient solution as it takes up server memory to buffer the output and delays the sending of first byte.
The best solution would be to find what is sending the output before the header call and delay the output if possible.
A good trade-off I found was to enable output buffering using ob_start at beginning and flushing the buffer just after the page <head> element is generated and all the needed headers are set. This way any further output is not buffered. The only thing to take care of is that all header calls are made before the ob_end_flush call.
The headers were sending correctly all along but I was checking the response of the file I was using and not properly getting the response from the CURL, if that makes sense! I just needed to use:
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

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.

why ob_start() must come ahead of session_start() to work in PHP?

I don't think it's reasonable.
Why is it actually such a rule?
In the "normal case", I don't think ob_start has to be called before session_start -- nor the other way arround.
Quoting the manual page of session_start, though :
session_start() will register internal
output handler for URL rewriting when
trans-sid is enabled. If a user uses
ob_gzhandler or like with ob_start(),
the order of output handler is
important for proper output. For
example, user must register
ob_gzhandler before session start.
But this is some kind of a special case : the thing is, here, that the order of output handlers is important : if you want one handler to modify things the other did, they have to be executed in the "right" order.
Generally, if you don't use that kind of handlers (Apache and mod_deflate do a great job when it comes to compressing output, for instance), the only thing that matters is that headers must not be sent before you call session_start (because, depending on your configuration, session_start sends cookies, which are passed as HTTP headers).
And headers are sent as soon as any piece of data has to be sent -- ie, as soon as there is any output, even one whitespace outside of <?php ?> tags :
Note: If you are using cookie-based
sessions, you must call
session_start() before anything is
outputted to the browser.
ob_start indicates that PHP has to buffer data :
This function will turn output
buffering on. While output buffering
is active no output is sent from the
script (other than headers), instead
the output is stored in an internal
buffer.
This way, output is not sent before you actually say, yourself, "send the data". This means headers are not send immediatly -- which means session_start can be called later, even if there should have been output, if ob_start had not been used.
Hope this makes things a bit more clear...
If by default your output_buffering is Off and you have been unfortunate enough to send a single byte of data back to the client then your HTTP headers have already been sent. Which effectively prevents session_start() from passing the cookie header back to the client. By calling ob_start() you enable buffering and therefore delay sending http headers.
session_start might want to modify the HTTP header if certain configuration options are set. One for example is session.use_cookies that requires to set/modify the Set-Cookie header field.
Modifying the HTTP header requires that there isn’t any output that’s already sent to the client as the HTTP header is sent right before the first output is sent.
So you either ensure that there is absolutely no output before the call of session_start. Or you use the output buffering control to buffer the output so that the HTTP header can be modified even if there already is output.
session_start() will register internal output handler for URL rewriting when trans-sid is enabled. If a user uses ob_gzhandler or like with ob_start(), the order of output handler is important for proper output.
For example, the user must register ob_gzhandler before session start.
But this is some kind of a special case. The thing is, here, that the order of output handlers is important. If you want one handler to modify things the other did, they have to be executed in the "right" order.
Generally, if you don't use that kind of handlers (Apache and mod_deflate do a great job when it comes to compressing output, for instance), the only thing that matters is that headers must not be sent before you call session_start (because, depending on your configuration, session_start sends cookies, which are passed as HTTP headers).
And headers are sent as soon as any piece of data has to be sent -- ie, as soon as there is any output, even one whitespace outside of <?php ?> tags :
Note: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser.
ob_start indicates that PHP has to buffer data :
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
This way, output is not sent before you actually say, yourself, "send the data". This means headers are not send immediatly -- which means session_start can be called later, even if there should have been output, if ob_start had not been used.
session_start(); should be called before any headers are sent out. ob_start() will suppress the output for a while and you can break this rule. Usually ob_start() on the top is a quick fix in case you are debugging something unknown; everything below works as expected (not just as written ;-)). I prefer to use ob_start() later to session_start().
In PHP, ob_start() is used to start output buffering. Output buffering captures all output sent to the browser and stores it in a buffer, allowing you to manipulate it before sending it to the browser.
When using sessions in PHP, it is important to call ob_start() before starting the session, as sessions rely on cookies, which are sent to the browser as part of the HTTP headers. If any output has already been sent to the browser before the session is started, the headers will have already been sent and it will not be possible to set the session cookies.
By calling ob_start() before starting the session, any output that is generated before the session is started will be captured by the buffer and will not be sent to the browser. This allows the session cookies to be set correctly, even if some output has already been generated.
In summary, ob_start() is necessary for session in PHP because it ensures that headers can be sent correctly even if there is output generated before the session is started.

Categories