PHP Sessions - Warnings - php

I asked the question "php warning - headers already sent after server move" yesterday and I have made changes since to try and fix the problem but im still not getting it!
I am working on code that has been made by another company! Im not moving the site off their server and putting it on ours but the my problem is that sessions are not working across the pages on the new server!
I am getting the warning:
Warning: session_start() [function.session-start]: Cannot send session
cache limiter - headers already sent (output started at
/home/com10002/public_html/bank/index.php:28) in
/home/com10002/public_html/bank/includes/quickform.php on line 3
In my index.php
include('includes/functions.php');
$activeTab = "navhome";
$sent = false;
$title = (isset($_GET['title']))? mysql_real_escape_string($_GET['title']) : 'Home';
$title = str_replace('-',' ', $title);
if($title != '') {
$sql = "SELECT *
FROM contents
WHERE name LIKE '%$title%'
LIMIT 1";
$result = #mysql_query($sql);
$row = mysql_fetch_assoc($result);
}
//Set page title
$pagetitle = (isset($row['name']) && $title != 'Home')? ucwords($row['name']) : "Bank Charges";
HTML..HEAD..META DATA AND TITLE TAGS..ECT
include('includes/header.php');
<div class="textarea">
<?php include('includes/rightcol.php'); ?>
<div id="contentvideo" style="display:none;"></div>
<h1><?=$row['h1'];?></h1>
<h2><?=$row['h2'];?></h2>
<?=$row['intro'];?>
<?php include('includes/quickform.php');?>
<?=$row['page_content'];?>
</div>
<?php include('includes/subnav.php'); ?>
and in quickform.php
if($_POST) {
session_start();
$error = false;
$captcha = false;
$sent = false;
etc.......
This is their code and currently works fine on the their server!
1) I have tried moving the session_start() to the top of index.php
2) Putting a session on both pages.
3) Removing white space before the session when it was in the index.php
My new version is the site is at www.compensation-claims.org/bank
Because this is not my code im not sure as to why they put the session in the quickform.php

A quick and dirty fix would be to activate output_buffering on your server, by modifying your php.ini file (and restarting Apache), setting something like this :
output_buffering=4096
The problem you have is because HTTP headers can't be sent if even only 1 character has already been sent ; by using that directive, you indicate that nothing should be sent before 4k of data have been buffered.
That's usually enough to buffer some white spaces that are present at the beginning/end of .php files, and are enough to cause that kind of trouble.
Note : this is a quick-and-dirty fix, but it might help you get the application working.
Of course, the best solution would be to remove any kind of output that is sent before calling session_start / or to move the call to session_start to the beginning of your PHP script.
One thing that often helps is to remove the closing ?> tag at the end of .php files, so you don't have any white space after it, as it doesn't exist anymore (yes, that's perfectly valid)
EDIT after having a second look at the given code :
In header.php :
You are doing some output (HTML code, like the div "textarea")
And, only then, you are starting the session with session_start
as some output has already been sent to the browser, the session_start cannot create the cookie, and fails.
So, you really need to move the session_start as high as possible : but it right at the beginning of index.php, for instance ; or, maybe, to get it everywhere, at the top of functions.php...
... But definitly NOT in the middle of some HTML output!
(What I said earlier about output_buffering is probably the reason why this (not good) code worked before)
This should solve the problem, I think...
Good luck, anyway !

Sounds like a UNIX character return is being sent to the browser because of how Windows handles carriage returns differently. One or more characters sent before sending headers will cause this error to occur. The alternative may be that the other server had output buffering enabled by a php.ini directive that was capturing and parsing any output before sending it to the client. This could have been the case for compression reasons. I would suggest comparing the php.ini configariton and seeing if gzip compression was enabled on the Apache server prior to the move.

You can use the ini_set() function in your script to set php.ini configuration values.
ini_set('output_buffering', 4096);

Related

session cache error only on two pages - All other pages are working fine

I developed a website from a developer. My website was working fine. All of a sudden I discovered that whenever I click on Contact Us link, I get an error
"Warning: session_start() Cannot send session cache limiter - heards
already sent (output started at /home/xxx/public_html/contact.php:1)
in /home/xxx/public_html/connection/config.php on line 2"
This was not happenning before. The developer is not giving me support and is ignoring my emails. So I searched and researched for it a lot on the Internet and found that there is something wrong in the way session_start() is defined.
Here is the code of contact.php
<?php
include("connection/config.php");
session_start();
?>
<?php
if(isset($_POST['enquiry2']))
{
.
.
.
}
?>
<!DOCTYPE html PUBLIC
.
.
.
<?php include "footer.php"; ?>
</html>
Code of config.php
<?php
session_start();
error_reporting(0);
if ($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '192.168.1.111')
{
$con=
.
.
}
else
{
$con=
.
.
}
error_reporting(E_NOTICE ^ E_WARNING ^ E_ALL);
require_once("logic/class.config.php");
.
.
<?php date_default_timezone_set("Asia/Kolkata");?>
In lot of articles I read that session_start() should be right at the top of the page so I reversed the second and third line of contact.php but it gave me same error pointing to contact.php file.
"Warning: session_start() Cannot send session cache limiter - heards
already sent (output started at /home/xxx/public_html/contact.php:1)
in /home/xxx/public_html/connection/contact.php on line 2"
Earlier it was pointing to config.php fle
Same thing is happening in registration page. I have three files register.php, register1.php and register2.php. The same error occurs only on register3.php when it loads the page and once again when submit button is clicked.
I request if someone can help me identify the problem.
Thanks.
EDIT
As suggested by Premalatha:
Removed session_start(); from contact.php -> but same warning.
Placed session_start(); on top of include("connection/config.php"); -> but same warning.
As suggested by Alok:
I dont know how to check if I am sending content or calling header somewhere before session_start(). The session_start() line is either on top or in the second line with first line being include("connection/config.php"); that I tried interchanging upside down with no help.
One thing I fail to understand that other .php files also have the same coding then why this warning comes only on contact.php? Similarly, register1.php, register2.php also have same coding but why the warning comes only while loading and unloading register3.php. All was working before, this started all of a sudden and I dont remember doing any changes in any of these files so the issue may be something else. I also wanted to try suggestion from wangpeng but I could not find the php.ini file anywhere in cpanel. Moreover, I did not figure out how to check if the file's code if it is UTF8-BOM. Also where exactly should i put OB_START() because i am unable to identify where is the header.
EDIT2
By the way, this warning does not affect the functioning of the site. The error just appears and then disappears. However, it disturbs the css, all fonts and images become bigger and the look of the page goes for a toss. Can someone tell me how to ignore this error so that the system doesn't show it at all?
session_start();
is already included in config.php file.
You can remove in contact.php file and it would start working without any issues.
If you still face any issues then you can place session_start(); line of code in contact.php above the include statement.
1.php.ini session.auto_start = 0 to session.auto_start = 1 .
2.check the file's code is UTF8-BOM? yes,UTF8-BOM to UTF8.
3.OB_START();before header
Headers already sent means PHP script sent the headers to the server already, and it cannot be modified now.
Which means before session_start() your script must be sending content or calling header to the server and and after sending it script is calling session_start() function which tries to modify the headers.
Solution in your case is to check you're not sending content or calling header some where before session_start() in both the scripts.
Update:
Try this,
Locate all the *.php files pointed in contact.php and find session_start(); in it.
Replace it with the following,
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Above code will make sure that you don't start the session again if it is already being started.
I never thought the solution would be this !
However, when I read same thing from four different people, I had to try this and it worked ! I had few leading, trailing and blank spaces in my include files. I got rid of them and my problem was solved.
Here is the article that helped me a lot
Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"
if you have blank space after php tag (or html or any output) in your include files then this error will come. -by Imdad
The reason for getting this issue is 99% likely to be trailing spaces at the end of your include files (yes - I know it sounds unlikely but just try it). Remove the trailing spaces, newlines etc... and all will be well. -by Chris B
a white-space before <?php also send for output and arise error. Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line -by Biswadeep Sarkar
For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:
<?php
require_once('mylib.php');
session_start();
?>
In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending. -by Ross

how to ignore redirection errors in php

I got this warning in php:
Cannot modify header information - headers already sent by (output started at
When I installed mysql, apache, and php separately but when I'm using Wamp the warning does not exist and the page redirects gracefully.
I have already tried setting the error reporting to only display errors and not warnings and what happened is that the warning didn't show up but the page also didn't redirect.
I know this is already considered bad practice but my code base has a lot of these codes and modifying them all might introduce new bugs to the code.
Is there any way to completely ignore this warning in php?
The classic way to avoid - and not ignore - this problem is with output buffering, ob_start() and ob_flush(). Start the buffering before any output, and finish with the flush explicitly, or it may do so automatically. This captures any output rather than printing it, and so any headers that are output are done so before any visible content.
Fixing the bug of things being output, from the filename you had in the error message is the best way to fix this though. Removing the closing '?>' from files when it's not needed might help.
This is an horrible practice but just set
error_reporting(0);
at the beginning of your script. Otherwise setit in php.ini
display_errors = Off
EDIT - probably you are outputting something before the redirect. I once spent three days debugging this and the reason sometimes is whitespace at the end of files or the fact that you output some HTML to the browser before the redirect.
I usually never close the php tag to avoid this
Even when you don't show your error your application will not work. This is because like the error said the headers are already sent. What this means is the following:
A browser requests your php file at the server. The server then executes this and sends back the resulting html. This error tells you that you are sending something back to the browser after you already sent the result of your php file. So I'd suggest you try to fix the error your getting instead of just not showing it.
You can't "ignore" this warning and redirect. The warning says so clearly:
Can't send headers! Headers already send by output!
This means that the header (the Location header cannot be sent because output was already sent. (Headers may only be sent before any and all output).
Please RTM, you need to fix your bugs, not ignore them.
The error is caused by you sending some sort of output before the header() function is called, the reason for that may be a lot of things, when unexpected, the immediate suspect is a whitespace at the beginning or ending of some file.
<?php //Note the space before the opening tag!
header("Location: this-will-fail.html");
?>
Please note that this error specifies exactly where in your code you've started to output data to the browser (see the output started at ...1, look for trailing white space \r, \n, tabs & spaces).
In theory, turning off the error reporting will not cause the page to redirect because the headers were already sent and therefore cannot be changed or added to.
What you should do if you need to redirect with data already sent is something like this:
if ( headers_sent() ) // Check if the headers were already sent
{
echo( "<script>document.location.href='$url';</script>" ); // Use client side redirect
die(); // Stop here
}
else
{
header( "Location: $url" ); // Use server side redirect
}
But the best thing would be to find out where the output started and fixing that (if possible).

session_start() error

I can't handle this error, please help me. It worked on my laptop but did not work on my desktop.
Why?
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at F:\xampp\htdocs\etest\index.php:1) in F:\xampp\htdocs\etest\common\header.php on line 3
The code:
<?php
ob_start();
session_start();
include("constants.php");
include("includes.php");
?>
Thanks for your kindness!
the error was at F:\xampp\htdocs\etest\common\header.php on line 3 but output was already started at F:\xampp\htdocs\etest\index.php:1
I assume you posted the header.php, but your index.php either has whitespace before the
<?php include() or outputs something other than a header on the first line.
the error is caused by line one of index.php, whatever is there. I'd guess whitespace.
In general, when you see "headers already sent", it means that you are trying to do something that requires an HTTP header to be set, but you have already sent content to the client. When using HTTP, you have to send the headers, then the content comes after. If you've sent content, you've missed your opportunity to send headers.
Start the session on top of the file.
direct afer the php tag when you make an echo or send some header before you get this errormessage.
<?php
session_start();
ob_start();
include("constants.php");
include("includes.php");
?>
Enable output buffering by configuration. This way it will start before anything else, so it certainly solves your problem. Although you should look at your code and find the cause of the present error, because it seems you do not fully understand your site yet.
After enabling output buffering by configuration, you no longer need to call ob_start() manually.
Create a file called .htaccess with this content:
php_flag output_buffering on
... or add this line to your php.ini:
output_buffering = On
use_only_cookies=0 to use_only_cookies=1 in php.ini file
I encountered the same problem in xampp 7.0.1 and this fixed it. Read it here.
Yes start the session on top of the file amd make sure you do not have a space before
<?php
Plus you can call session_start(); only one time
session_start() must be called before there is ANY other output. The error is telling you that output started on index.php line 1. The call to session_start() must be placed before that.
Put this code inside includes.php
ob_start();
session_start();
And remove the same code from every other page.
Also make sure that in your files there is no whitespace before the initial
(specifically you are getting the error because something is wrong on the first line of index.php not of header.php)
I was getting this even when I had it at the top of the file.
Problem INVISIBLE UTF8 CHARACTER
Solution
Was to delete the file and make a new one starting with <?php and then copy everything after the php into the new one. (Don't copy the beginning of the file).

PHP session_start() fails to create session

These are my first 5 lines in my index.php:
<?php
session_start();
if (!isset($_SESSION['cart'])) $_SESSION['cart']='';
$page = $_GET['page'];
?>
and so on..
I'm looking at the sessions trough the firefox->firebug->firecookie plugin and a session is not created.(I am sure of it because the cart that worked yesterday doesnt work today.)
Any ideas why this might happen and how to fix it ?
I found this when enabling errors:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/controll/public_html/metalkonsult.com/index.php:1) in /home/controll/public_html/metalkonsult.com/index.php on line 2
I explored further - something IS sent to the browser but I dont know where its coming from. I did a var_dump(headers_list()); on the first line and this is what I get:
array(2) { [0]=> string(23) "X-Powered-By: PHP/5.2.6" [1]=> string(23) "Content-type: text/html" }
How do I turn this off ? What's sending it ?
I set session.auto_start = 1
in php.ini in the website folder
sessions work now..
dont know what caused the problems but problem is temporarily fixed
If the white space I see before your php opening tag (<?php) is in your source code too, then this is the reason :) Make sure that no output has been done before your session_start call.
You can check with firebug the exact output, by going to the net tab, locating your PHP file transfer, expanding it, and seeing the Response tab. You could put a print just after the session_start and see where it appears... it should be the very first thing.
Otherwise, if you have php errors directed to log, go and see the log if there is anything in it. Finally, make sure that the browser is displaying session cookies too: some browsers don't show them.
Something is being sent to the browser first which is causing the headers to be sent. Check your code to make sure that there isn't even a single space before your PHP code.
Some editors add an invisible UTF-8 byte order mark at the beginning of the file. Depending on the various server software versions, it may or may not be sent to the browser. Could you check a hex dump of your source code and make sure the first 5 bytes are 3c 3f 70 68 70?
Works for me. Make sure your server has write access to the folder where session data is kept (check your session path: http://php.net/manual/en/function.session-save-path.php)
<?php
session_start();
$_SESSION['cart'] = "test<br />";
print $_SESSION['cart'];
if (!isset($_SESSION['cart'])) $_SESSION['cart']='';
print $_SESSION['cart'];
//blank it out
if (isset($_SESSION['cart'])) $_SESSION['cart']='';
print $_SESSION['cart'];
?>
outputs
test
test
#Palantir: And the whitespace doesn't matter.
Is that the first PHP page called or is it included from another one?
If it is the first, try enabling output_buffering on php.ini. You may then be able to see what is being sent before by calling ob_get_contents()
I had this problem caused by two different things:
1- there were an empty line at the beginning of the file case the php 5.2 to push 'headers already sent' warning.
http://board.phpbuilder.com/showthread.php?10310794-RESOLVED-Warning-session_start()-Cannot-send-session-cookie-headers-already-sent
if < ?php is at line 2 of your script and a blank line is above it then
that can cause problems such as the php header function not working.
2- PHP output_buffering was turned off by default.
If you're using shared hosting and code works on localhost maybe this can be the reason.
just set these parameter in php.ini or local .user.ini
output_buffering=4096

Redirecting if statement not working

Hey, I am trying to make an if statement that redirects them to a different page if true, simple right?
I am not sure why this is not working but I am using:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
$userid = strtolower($_SESSION['X2X2']);
$getuser = mysql_query("SELECT * FROM XXXXXX WHERE X2X2 = '$userid'");
$info = mysql_fetch_array($getuser);
$id = $info['X3X3'];
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
header('Location: http://beta.XXXXX.co.uk/purchase.php');
mysql_close($con);
}
When I put
<?
echo $_POST['accounttype'];
?>
And I get back
Paid User - £2 p/m
Which is correct?
Any help would be appreciated,
Thanks.
Looks like you want to call exit() before the close brace on your if statement.
The documentation for header has example code like this:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
The end bit of your if statement really ought to be:
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
mysql_close($con); // do this before sending a redirect header
header('Location: http://beta.XXXXX.co.uk/purchase.php');
exit();
Also, header doesn't work if you've already sent any output, per this warning from the documentation for header:
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.
As it seems to depend on £, you have several possibilities depending on which values $_POST['accounttype'] can have.
First I suggest you try:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
(as £ is £ in HTML).
If this doesn't work, what is the part of the string, that makes it unique? Paid User or 2 p/m? If any of these, it is sufficient to check against a substring like:
if (substr($_POST['accounttype'],-5)=='2 p/m'){
or
if (substr($_POST['accounttype'],0,9)=='Paid User'){
or any combination (avoiding £).
You haven't by any chance already output something to the browser have you? If you modify the location header after using the echo or print statements, it will issue a warning which you probably won't see unless you have verbose errors or logging turned on.
I know this can happen with UTF-8 files in some versions of PHP - the byte order mark (BOM) of the UTF-8 file are output before the PHP script starts execution, which prevents the location header from being sent.
Altering the HTTP header with header requires that the HTTP header has not been sent yet. This can be one reason for why it doesn’t work for you as the HTTP header is sent together with the first output of your script (any output including text before <?php).
When you set error_reporting to E_ALL and display_errors to true, PHP will display you all errors immediately. This can help you to determine the cause of you error.
My first inclination would be to check if there are any extra characters on your POST data by trying the following:
if (trim($_POST['accounttype']) == 'Paid User - £2 p/m') {

Categories