The previous attempt at PHP was on a Windows system, now I'm on a Ubuntu (Hardy) laptop, and I had a little issue with getting the session to work... And had trouble finding the solution... The warnings I got were the following...
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /var/www/Justin/Experimentation/MyPage.php:8) in
/var/www/Justin/Experimentation/MyPage.php on line
8
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /var/www/Justin/Experimentation/MyPage.php:8) in
/var/www/Justin/Experimentation/MyPage.php on line
8
Here is a simple version of what caused the error:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<?php session_start(); ?>Now the warning message said "Cannot send session cache limiter - headers already sent".
I'm going to hazard a quess as to how PHP's page processing model works...
- The processor starts processing the file. Any PHP code is processed.
- When it gets to the first bit of HTML (in this case the DOCTYPE) the header information is sent to the client browser
- The rest of the page is processed as per normal
Update:I found out later that this is essentially correct.
Any output like a blank line or output from php code will cause the Http headers to be sent to the user agent: See
here Sessions usually work by sending a cookie to the client (user agent) so that the server can keep track of which session relates to which user agent.
Now the
session_start() call is "
after" the first bit of Html, the headers have therefore already been sent, and we get this warning... and a non-functional session!
The RuleAny time you need to manipulate the header information or any time you "do" anything that itself manipulates the header information, you need to execute the PHP code BEFORE ANY Html on the page!
So you would do this:
<?php session_start(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Then, of course, the session will be started, the session cookie added to the header information, then the first bit of Html is hit and off goes your cookie to the user agent(browser)
So simple... So annoying to figure out... I better remember this on! I'm going to need it!