Solve "Cannot modify header information - headers already sent by *.php"

Warning: Cannot modify header information - headers already sent by somefile.php (output started at somefile.php:###) in somefile.php on line ###

This Warning is shown by PHP when you use the header function to output headers or use the setcookie function to set cookies after any echo or content which is not inside PHP tag. <?php echo "Hello World"; header("Location: /redirect.php"); ?> Hello World !!! <?php header("Location: /redirect.php");?> Both should throw this warning. You can disable this warning by turning the error_reporting to OFF using error_reporting(0); , which is pretty much the not way of doing things. In HTTP Headers are sent before the actual content so if you are going to use header function after outputting the contents, it is likely to not work.

How do I solve this Warning Cannot Modify Header Information ?

In order to solve this issue you have to make sure you dont echo or print any output before using header or setcookie function. Make sure the control passes through these functions and then to the output part.

I am sure I dont output anything before calling header or setcookie

Just see all your files for white spaces or empty new lines. For example if you include a file before using the header or setcookie functions, make sure the file does not have a closing php tag (?>) at the end of the file. This is recommended by PHP so that stray white space or new line characters at the end of this included file gets outputted. //<-- A new line on top ! Oops. <?php header("Location: /redirect.php");?> // <-- A blank line at the end?

I still want to output first and then use header function

In that case you can use output buffering functions to buffer your output automatically before senting any output and the output is sent as a chunk at the end. The following code snippet shows this : <?php ob_start(); ?> Hello World !!! <?php setcookie("name","value",100); ?> Again !!! <?php ob_end_flush(); ?>

But my code is already done and I dont want to add ob_* functions to it !

You can turn on buffering in PHP on by default using php.ini. Look for output_buffering , The following shows the mentioned part of the php.ini file. Set the value as On and restart Apache server. ; Output buffering allows you to send header lines (including cookies) even ; after you send body content, at the price of slowing PHP's output layer a ; bit. You can enable output buffering during runtime by calling the output ; buffering functions. You can also enable output buffering for all files by ; setting this directive to On. If you wish to limit the size of the buffer ; to a certain size - you can use a maximum number of bytes instead of 'On', as ; a value for this directive (e.g., output_buffering=4096). output_buffering = On

Video to fix your warning cannot modify header information

<object width="600" height="410"> <param name="allowfullscreen" value="true" /> <param name="allowscriptaccess" value="always" /> <param name="movie" value=";;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" /> <embed src=";;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="600" height="410"> </embed></object> Hope this solves all your annoying
Warning Cannot Modify Header Information :) 17 Mar, 2010
Comments (47)
  • You know what would be a GREAT idea ?

    Simply to post a sample code using headers that works. I went through all these convoluted posts and am not better. Actually quite confused. This page is a list of code that does not work, and I still do not understand where ob_start should be placed ...

    Sorry to be blunt, but teaching by example is often much better than cryptic dialogs and answers. Will appreciate a written example code, indeed. Thank you in advance.

    By Mitch Bujard on 02 Nov, 2012
  • For me the eror was consistenr until I removed BOM formatting. You can easy doit with Notepad++ on Encoding menu choose encode Utf8 without BOM and save

    Good luck

    By Alex on 10 Aug, 2012
  • Hello, I need help please. I add ob_start() and that stops the warning. However, my javascript function stops working as well. Basically, I need to use header() to export data to an csv file. Everything was okay until I add this css stuff to help freeze while getting the data and unfreeze the webpage before the File Open/Save dialog pops up. The problem is that my program can freeze the webpage but cannot execute the js function to unfreeze the webpage. Please help out. Thanks in advance. Below is the essential part of the task: (I tried to make it as short as possible.) <?php ob_start(); $hearingform = ' <html> <head> <style type="text/css"> ..... </style> <div align="center" id="FreezePane" class="FreezePaneOff"> <div id="InnerFreezePane" class="InnerFreezePane"> </div> </div> <script type="text/javascript"> function FreezeScreen(msg) { scroll(0,0); var outerPane = document.getElementById("FreezePane"); var innerPane = document.getElementById("InnerFreezePane"); if (outerPane) outerPane.className = "FreezePaneOn"; if (innerPane) innerPane.innerHTML = msg; } function unFreezeScreen() { var outerPane = document.getElementById("FreezePane"); outerPane.className = "FreezePaneOff"; }'; // some code to pull data from the database... echo '<script type="text/javascript">unFreezeScreen();</script>'; /*send data to an excel file*/ header("Content-type: application/csv"); header("Content-Disposition: attachment; filename=$filename"); echo $data; } //END post IF ob_flush(); ?>
    By dominico on 05 Jul, 2012
    • ob_start does not affect javascript

      ob_start and ob_flush is most likely to not cause any issues on javascript, please check console for any likely javascript errors.

      I think you have missed an ending script tag after the unFreezeScreen definition.

      By digitalpbk on 05 Jul, 2012
      • Hi digitalpbk,

        Thanks for your response. I think I did have the ending tag "}" if that is what you meant.

        function unFreezeScreen() {
        var outerPane = document.getElementById("FreezePane");
        outerPane.className = "FreezePaneOff";

        The js script above didn't run after I added ob_start(). If I take off the ob_start then it runs but I also get the header warning errors.

        By dominico on 06 Jul, 2012
        • Script ending missing

          I meant </script> tag.

          By digitalpbk on 06 Jul, 2012
  • Thank you! One of the plugins uses setcookie, and I put ob_start / ob_end_flush to no avail. I fixed my php.ini for output buffering and finally it does the job!

    By Sari on 04 May, 2012
  • <?php ob_start(); ?> <?php ob_end_flush(); ?> 101% works for me . thank you sir !
    By Rajendra Singh on 06 Apr, 2012
  • hello..i got the same problem..had tried all the option here..noting work..this the error = Warning: ini_set() has been disabled for security reasons in /www/ on line 2 Warning: Cannot modify header information - headers already sent by (output started at /www/ in /www/ on line 28 Warning: Cannot modify header information - headers already sent by (output started at /www/ in /www/ on line 29 And this my code... <?php ob_start(); abstract class Controller { protected $registry; protected $id; protected $layout; protected $template; protected $children = array(); protected $data = array(); protected $output; public function __construct($registry) { $this->registry = $registry; } public function __get($key) { return $this->registry->get($key); } public function __set($key, $value) { $this->registry->set($key, $value); } protected function forward($route, $args = array()) { return new Action($route, $args); } protected function redirect($url, $status = 302) { header('Status: ' . $status); header('Location: ' . str_replace('&amp;', '&', $url)); exit(); } protected function getChild($child, $args = array()) { $action = new Action($child, $args); $file = $action->getFile(); $class = $action->getClass(); $method = $action->getMethod(); if (file_exists($file)) { require_once($file); $controller = new $class($this->registry); $controller->$method($args); return $controller->output; } else { trigger_error('Error: Could not load controller ' . $child . '!'); exit(); } } protected function render() { foreach ($this->children as $child) { $this->data[basename($child)] = $this->getChild($child); } if (file_exists(DIR_TEMPLATE . $this->template)) { extract($this->data); ob_start(); require(DIR_TEMPLATE . $this->template); $this->output = ob_get_contents(); ob_end_clean(); return $this->output; } else { trigger_error('Error: Could not load template ' . DIR_TEMPLATE . $this->template . '!'); exit(); } } } ob_end_flush();?> any suggestion plez...
    By jomtido on 05 Apr, 2012
    • Check index.php for output statements

      Please check the file at /www/

      And add ob_start() ob_end_flush() to the index.php

      By digitalpbk on 24 Apr, 2012
  • My problem was solved when i used put all php code in a single php tag


    my code


    it means when we use

    some code
    any html coding
    some code

    then it was giving error
    but i have copied all code in single php tag and really my problem was solved

    By Atul Kumar on 19 Mar, 2012
  • Hello, I have this report in my server's error_log: Could not set cookie. Headers already sent. My header.php starts like this: <!DOCTYPE html> <html xmlns="" xmlns:fb=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div id="fb-root"></div> <script type="text/javascript"> window.fbAsyncInit = function() { FB.init({appId: '<?php echo $app_id;?>', status: true, cookie: true, xfbml: true}); and as for the index.php that is the file that starts the whole thing it starts like this: <?php require_once 'config.php'; require_once 'facebook.php'; //////end constatnt $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $fb_app_secret, 'cookie' => true, Any Suggestions? Thank you very much in advance.
    By Dimitris on 30 Jan, 2012
  • here is the code....this is showing warning:header already sent..i have used ob_start() and ob_end_flush() in this code..still it's giving the warning.. <?php ob_start(); mysql_connect('localhost','root',''); mysql_select_db('rajashiv_wrdp1'); $insert=mysql_query("INSERT INTO comment (name,comment) VALUES ('$_POST[name]','$_POST[comment]') "); if($insert) { header('Location:http:edit.php'); }ob_flush(); ?> this error can occur Cannot modify header information - headers already sent by (output started at /home/rajashiv/public_html/data.php:2) in /home/rajashiv/public_html/data.php on line 9
    By nitn on 26 Jan, 2012
    • Space before <?php

      Is there a space before <?php tag?

      By digitalpbk on 29 Jan, 2012
  • php to stream mp3s

    I was using a code to substitute the url adress with an id to stream mp3s. Adding ob_ functions fixed the problem for me.
    Thank you for the solution by the way.

    By Guney Ozsan on 22 Nov, 2011
  • ob_start worked

    Great Guy!!! <?php ob_start(); ?> did the job.

    By Treasure on 15 Nov, 2011
  • The Use of @

    I tried to use @header("$location:mylocation"). It just works.

    By Tian En on 05 Oct, 2011
    • Use of @

      @ just suppresses any warnings on that line. This method is not recommended.
      By digitalpbk on 06 Oct, 2011
  • Problem with "own wiki an installing extensions"!!!!!!!!!!!!!!!!

    Warning: Cannot modify header information - headers already sent by (output started at /users/knowpedia/www/Knowpedia/LocalSettings.php:1) in /users/knowpedia/www/Knowpedia/includes/WebResponse.php on line 22

    what can i do, to make changes with extensions effect? hope everyone can help me.


    By sandro on 13 Sep, 2011
  • Thank You! This was driving me nuts!

    Putting this at the top of the file:
    <? ob_start(); ?>
    and this at the bottom
    <? ob_flush(); ?>

    Did the trick for me! The project I'm working on was a WordPress install as well. Was doing some custom stuff and this post helped me fix it! Thanks again.

    By Tosh on 06 Sep, 2011
  • Warning: Cannot modify header information - headers already sent

    i got the same problem
    Warning: Cannot modify header information - headers already sent by (output started at /......./header.php:112) in /xxxxx.php on line 24

    but header file line 112 is below code
    <style type="text/css">
    why is that..??
    im tired to sloved this problem..please help me
    display errors off in php.ini
    but still its gave the same error
    i cant fix..
    please help me'

    By rasika on 11 Aug, 2011
    • What is on line 24?

      It says the output started on line 24, verify the line, or else try any of the methods above. ob_start(); ob_funcs()
      By digitalpbk on 16 Aug, 2011
  • You are awesome!

    Thanks a ton man! One of my client's came up to me with this problem in one of his old code! Had to go over the whole CMS code looking for that blank space hidden somewhere haha.. But in the end, your php.ini edit worked like a charm! :) You are awesome! thanks.

    By Sumeet Chawla on 04 Aug, 2011
  • header:location problem

    here is the code....this is showing warning:header already sent..i have used ob_start() and ob_end_flush() in this code..still it's giving the warning..
    <?php ob_start(); ?>
    <html xmlns="">
    <title>Untitled Document</title>
    <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    <style type="text/css">
    .style1 {
    font-size: 24px;
    font-weight: bold;
    .style2 {font-size: 18px}
    .style3 {color: #FFFFFF}
    <?php include("cdb.php");?>
    die("<br><br><br>you did not fill in a required field...");
    $check=mysql_query("select * from adminlog where admin_name='".$_POST['name']."'");
    die("<br><br>that user does not exist in ur database");
    die("Incorrect password,please try again");
    header("Location:status.php");}}} ?>
    <?php ob_end_flush(); ?>

    plz help me to solve this problem...:( :(
    thnx in advance sir..

    By Anonymous on 27 Jul, 2011
    • Spaces before ob_start ?

      Is the code complete ? Make sure you dont have any spaces before
      By digitalpbk on 28 Jul, 2011
      • thnx a lot..:) now the same

        thnx a lot..:) now the same code is running...

        By Anonymous on 29 Jul, 2011
  • redirect user in php : no header already sent problem

    if u too got fade up with the error in php page...

    "headers already sent output started by ........."

    and want to redirect your user to new page try this simple script

    hmmn after searching a lot simply use in php

    echo "<script>location.href='service.php';</script>";

    you can place it anywhere (in condition statement, in body, after html tags ) no header already sent problem ...

    By peace4each on 23 Jul, 2011
    • Header redirection using script

      This does not work unless the echo is enclosed in a script tag. This is front end browser redirection example using javascript, so not the best method, since there is no fallback when javascript is not present.
      By digitalpbk on 24 Jul, 2011
  • Header Problem Solved

    Thank digitalpbk for grateful suggestion.
    I solved "Cannot modify header information - headers already sent by" problem by using ob_start() and ob_end_flush() code.

    // my code...........................


    By Mehedi Hasan Nahid on 22 Jul, 2011
  • Header

    Hi everyone,

    I'm experiencing similar challenge, the line its making reference to is like this:


    if (Navigator::isRequestedUnderLegalURI()){

    $uri = Navigator::getUri();

    //$page_config = new PageConfig($uri);

    $page_config = PageConfig::getPageConfig ($uri);

    // the Responder!!!

    if ($page_config->PageExists()){

    $page_content = System::getPage($page_config);

    echo $page_content;

    please what do I change here?


    By Anonymous on 05 Jul, 2011
  • Hello

    It is very good blog.I am also looking for this from a long time.Many people like to visit here.I have seen many things over here.It is very good.

    By Friv Games on 05 May, 2011
  • Good Post...

    Good Post...

    By Nancy on 29 Apr, 2011
  • can't undersatnd how can do

    can't undersatnd how can do it??

    By Rakeback on 27 Apr, 2011
    • What part do you need help with ?

      What part do you need help with ?
      By digitalpbk on 27 Apr, 2011
  • Thank you!!!! This was

    Thank you!!!! This was extremely helpful! Amazing what one space can do...

    By blakemathews10 on 17 Apr, 2011
  • Thanks!!

    thanks alot, edit php.ini file solve my problem on my client site.

    By Outdoor Garden Lighting on 16 Apr, 2011
  • Its good idea

    Thanks for the help it will work for me.
    A good idea is to add gzip compression.

    By Wycieczki on 08 Mar, 2011
  • cannot modify header help

    thanks for the info,

    i have the same situation but it didnt worked in me.
    i am hosting my site in

    and i have this problem

    output started at /www/ in /www/ on line 56

    Warning: Cannot modify header information - headers already sent by (output started at /www/ in /www/ on line 57

    i already put the ob_start and the ob_flush, i followed your instructions but nothings happen, still got the same problem.

    can you please help me?
    im a newbie here. so thanks a lot .. :)

    By Anonymous on 08 Mar, 2011
    • Where have you put the ob_* ?

      Can you tell me where you have put the functions ?
      By digitalpbk on 08 Mar, 2011
  • same problem

    i have the same problem, but anything of your tips resolved my problem :( what i can do, all in seo pack caused problem in my header.

    By tech on 22 Feb, 2011
  • Thnak You

    i have visited almost all blogs , but you are the great man who give me the proper solution . you save my life by ob_start(); .
    Thank you very much .

    By Sajan Mullachery on 13 Jan, 2011
  • Thanks for the explanation and additional information

    Had the same problem, but as publishing in a CMS I could not turn on output_buffering. The next Problem was the inclusion of php-Files: They were strangly included by a html-Tag npsobj so I couldn't force the header-modification to be made before html-Tags were included. I also couldn't modify the code to have ob_start(); before outputting (which also would have left my php-Code untouched...) So: I was reeeally greatful to understand the hole header-modification issue to work out the above mentioned problems:

    Insert the path of your php-file to a the action-Attribute of a form: When clicking the submit-button a new page is enforced starting without output
    --> No Problems!

    By armiriel on 10 Jan, 2011
  • Thank you so much

    to all of the blog and forums I'd visited, your blog solved my problem.

    By Anonymous on 30 Nov, 2010
  • ob_start redirect

    Quality solution, was having trouble with conditional redirects as old developer used meta refreshes, this trick solved my issues

    many thanks

    By SEO Birmingham on 25 Oct, 2010
  • your my hero :D

    thanks alot, edit php.ini file solve my problem on my client site..

    By Dev on 19 Oct, 2010
  • ob_start();

    Awesome! I included ob_start(); in every php file that had errors and it did the job~!

    By Nadine on 20 Aug, 2010
  • Thank you.

    Good work.
    ob_start(); fixed my problem.

    By Hakan Atil on 07 Aug, 2010
You may also like
On Facebook
Email Newsletter