Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

PHP header problems

I have seen these errors before but I guess I just never fully understood how to fix them:

Warning: Cannot modify header information - headers already sent by (output started at /path/to/file/history.php:26) in /path/to/file/header.php on line 5

This is my code in history.php on line 26:

<?php include('inc/header.php'); ?>

and this is the code on lines 1-5 of header.php:

<?php
if(isset($_COOKIE['cookiename'])){
  $logged = true;
  $username=$_COOKIE['cookiename'];
  setcookie('cookiename',$username,time()+60*30,'/',"","",true);

how do I get rid of this error?

5 Answers

I see. Looking at it again. I think you set this on line 26?

it looks like the cookies are sent in the HTTP response header, and the html content already started and it cannot go back and add the cookies.

My last attempt would be to move your include header all the way on Line 1, before any HTML tags, and below the doctype. Where the set cookies( ) are all the way on top. That way the cookies can be set before any outputs. I can't see all your codes but that my last solution. Good luck.

Instead of using include( ), maybe try using

require_once('inc/header.php'); Hope that can fix it.

thanks, but I have tried that already... didn't work. Randy Hoyt , Hampton Paulk , any suggestions?

Hi Wendell,

Can you post the first 26 lines of that file?

Do you have any blank lines in your php files before the opening php block?

You want to make sure that nothing is being output to the page before setcookie

Oh good heavens I see the problem. Chris P while having html before the include, so I just took that out of the header file and let all the cookies be set at the beginning of the history.php and shabam! problem solved. I forgot that html counts as output

Yay, I am Glad you solved it.