Wednesday, June 19, 2013

[PHP][Solved] Cannot modify header information, example for ob_start() and ob_end_flush ()

[PHP][Solved] Cannot modify header information, example for ob_start() and ob_end_flush ()

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\test\index.php:10) in C:\xampp\htdocs\test\index.php on line 23

Mainly, there are 2 methods to solve it.

  1. Method 1 is open the "php.ini", set output_buffering = On, I won't discuss so much about this method here (cos I'm using hosting, can't edit that), If you get some interests in this method, give you 2 links to know more:
    How to Adjust PHP output buffering:
    http://www.ehow.com/how_12229788_adjust-output-buffering-off.html
    PHP output buffering Value:
    http://www.php.net/manual/en/outcontrol.configuration.php#ini.output-buffering


  2. Method 2, this solution is work for using hosting service
For anyone trying to set cookies after the header output, this seemed to fix it for me. You put an “ob_start();” before setting the cookie, and “ob_end_flush ();” after.

And right now I show you the code for my case :

 Original Coding:
<?php
ob_start();
session_start();
require "app_config.php";
if (isset($_POST['submit']))
{
$query = "SELECT password FROM users WHERE username = '" . $_POST['username'] . "';";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo "{$query}"."<br />";
echo "_POST[\'password\'] :"."{$_POST['password']}";
if ($row['password'] == $_POST['password'])
{
$_SESSION['username']=$_POST['username'];
$_SESSION['password']=$_POST['password'];
header ("Location: ../main.php");
exit;
ob_end_flush ();
}
else
{
echo("don't match");
}
}
?>

After Edited (Added the code in red):
<?php
ob_start();
session_start();
require "app_config.php";
if (isset($_POST['submit']))
{
$query = "SELECT password FROM users WHERE username = '" . $_POST['username'] . "';";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo "{$query}"."<br />";
echo "_POST[\'password\'] :"."{$_POST['password']}";
if ($row['password'] == $_POST['password'])
{
$_SESSION['username']=$_POST['username'];
$_SESSION['password']=$_POST['password'];
header ("Location: ../main.php");
exit;
ob_end_flush ();
}
else
{
echo("don't match");
}
}
?>

Refer link:
http://stackoverflow.com/questions/4620977/php-output-buffering
http://support.godaddy.com/groups/web-hosting/forum/topic/output_buffering/

No comments :

Post a Comment