如何使用php将cookie从一个页面传递到另一个页面

时间:2012-11-13 21:49:02

标签: php cookies setcookie

  

可能重复:
  “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"

 ?>

我想这是一个语法错误,但我知道太少或没有PHP找到它。有什么问题?

2 个答案:

答案 0 :(得分:2)

<?php
 session_start(); 

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

很好,至少你不要忘记在设置会话密钥之前运行session_start()

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

 setcookie('PagetoShow', $_SESSION); 

这是有问题的。 Cookie是在标题字段中发送的,但您已通过回显某些内容来刷新标题。

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

此处存在语法错误,您需要为if-body添加括号:

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

一些文档:

答案 1 :(得分:0)

setcookie的第二个参数需要是一个字符串 - 你传递一个数组($ _SESSION)。你可以这样做:

 $_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"