-3

Possible Duplicate:
“Warning: Headers already sent” in PHP

<?php
 session_start(); 

 $_SESSION['page'] = "test.php";

 echo "Page to load in iframe = ". $_SESSION['page']; 

 setcookie('PagetoShow', $_SESSION); 

 if(isset($_COOKIE['PagetoShow']))
$Page = $_COOKIE['PagetoShow']; 
echo "Page to load in iframe = ". $Page;
 else
$Page="welcome.php"

 ?>

I guess it is a syntax error, but I know too little or nothing php to find it. What is wrong?

Community
  • 1
  • 1

2 Answers2

2
<?php
 session_start(); 

 $_SESSION['page'] = "test.php";

Good, at least you don't forget to run session_start() before setting a session key.

 echo "Page to load in iframe = ". $_SESSION['page']; 

 setcookie('PagetoShow', $_SESSION); 

This is problematic. Cookies are sent in a header field, but you flushed the headers already by echo-ing something.

 if(isset($_COOKIE['PagetoShow']))
$Page = $_COOKIE['PagetoShow']; 
echo "Page to load in iframe = ". $Page;
 else
$Page="welcome.php"

There is a syntax error here, you need to add parentheses for the if-body:

if(isset($_COOKIE['PagetoShow'])) {
    $Page = $_COOKIE['PagetoShow']; 
    echo "Page to load in iframe = ". $Page;
}

Some documentation:

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
0

The second argument to setcookie needs to be a string - you're passing an array ($_SESSION). You can do:

 $_SESSION['page'] = "test.php"; 

 setcookie('PagetoShow', $_SESSION['page']); // <-- this is the only change needed

 if(isset($_COOKIE['PagetoShow']))
   $Page = $_COOKIE['PagetoShow']; 
   echo "Page to load in iframe = ". $Page;
 else
   $Page="welcome.php"
swatkins
  • 13,530
  • 4
  • 46
  • 78
  • it doesn't matter if it is a string, the cookie is still set (`page=Array`). The problem is that something is already printed and therefore the cookie header cannot be sent. – Lekensteyn Nov 13 '12 at 21:53
  • Oh, makes sense. i've updated my answer to fix that "header cannot be sent" error. – swatkins Nov 13 '12 at 21:54
  • Even though he calls setcookie on that page, the cookie won't be available until the next page request. I think that might be his confusion. – Kyle Nov 13 '12 at 21:56
  • @Kyle - good point - I guess I was assuming it was separate requests (the reason to use cookies in the first place) – swatkins Nov 13 '12 at 21:57
  • Thanks for the info on that the cookie isn't available until the next page request, for I had it all on one page just for testing purposes. But it still doesn't work, I get a 500 error message – Chatrine Karima Nov 13 '12 at 22:01
  • Well then, we'll have to see some more code. – swatkins Nov 14 '12 at 13:47