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.
Related
A PHP script (for booking an event) exits to an HTML page for a ‘Thank you for your booking’ etc message with a usual:
header ("Location: http://www.thankyou.com/")
at the head of the script.
The script now also needs to exit to other HTML pages (‘Sorry – no spaces available’ etc) where the page URIs are only determined later in the script. It could issue more header function calls to replace the original header but this makes it vulnerable to accidentally inserted spaces.
This must be a common requirement; what please is the best way to achieve it?
As far as no output is sent you can set headers (including the Location header for redirect) wherever you want in your script. There is no other better solution. Of course you would typically only do the operations you need to determine the destination of redirect and then redirect and exit script immediately, so redirects will be rather in the beginning of your script.
You should also place redirects in some predictable place, e.g. in your controller object or request validation function. It is not a good idea to have redirects scattered over many unrelated places, like inside many nested function calls etc.
If you have problems with accidental spaces, you should repair your scripts or use output buffering functions to buffer your accidental output and flush it only after all necessary headers has been sent.
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
I'm writing a little PHP authentication library(please hold off the "don't write your own". I've done this before). As part of my library I want to be able to "abort" execution in some cases.
For instance, take this example:
<html>
<head></head>
<body>
<?php
$auth=...
$auth.RequiresInGroup("admin");
?>
</body>
</html>
What I want RequiresInGroup to do is basically check if a user is logged in (by looking at the cookies and such).. and if they are not logged in or in that group, then it needs to send back a 401 error and do a server-side redirect to a not authorized page.
I know that I could move my <?php.. statement bit above <html> to make this work, but I'm trying to cover all possible use cases(including poor code design).
Is there a way in PHP to basically hold off on sending content to the client until the end of the request or some similar way to send different HTTP headers in the middle of execution and then exit out of the script?
You need to read the "control output buffering section" of the manual http://www.php.net/manual/en/ref.outcontrol.php
Headers themselves are not sent until your first bit of output - then the response code gets sent, followed by customer headers you have set. You can see if they have been sent using headers_sent() function. But you can't actually cancel headers once you've set them.
So buffer up what you need to send, then spit out the buffer at the end of the application.
Edit: another way of doing this (and the way I prefer, although it relies on a global or singleton class, that can both be frowned upon) is to create your own "output" class. Set that as a global (or singleton) and append output to that. Then you can send headers willy-nilly, and pump your output at the end of execution. Not as "unit test friendly" as ob_functions, but easier to debug and control.
so apparently if you do this:
<?php
echo 'something';
header("Location: http://something/");
?>
it will not work because there is an output preceding the header...
is there any other alternative php redirection method that works straight from php without installing anything and in which it will still work even if there's an output preceding it so that I don't have to worry about making sure that there is no output before, etc...
not, unless you do something in javascript or html tags in the page that you output itself
if preceding output is a problem
you can also use output buffering, see ob_start, ob_get
to get around that
There is no other way to do a php redirect, but you can fool it to still work even with code prior. You would buffer the content and only output it if there is no redirect or reaches the end of the script. Note: this may be resource heavy in some cases.
ob_start()
....CONTENT...
ob_end_flush();
There are no ways in PHP except using header()... before output is sent (headers be already sent)...
You can either use meta refresh in HTML that is set at zero seconds, or javascript.
But I wouldn't recommend javascript as some will have it disabled.
You could use a meta refresh tag.
You understand why this is impossible, right?
As soon as you echo "something" you have sent content to the client, and as part of that client headers were already sent. You can't retroactively modify headers you already sent, and you can't make two responses to one HTTP request.
ob_start() and ob_end_flush() will buffer the output instead of sending it to the client, which will allow you to get around this problem, BUT
a better solution would be to:
separate your logic code from your template so that you don't write anything to the screen until you already know you aren't going to redirect.
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.