关于PHPsession概念

时间:2013-09-19 07:52:09

标签: php session

shopping.php

<html>
<head>
<?php 
if(isset($_POST['sub'])){
    $a=$_POST['prod'];
    $b=$_POST['qty'];
    $_SESSION[$a]=$b;    
}    
?> 
</head>
<body>
<form method="post" action="Billing.php">

Select any Product:
<select name="prod">
   <option>Nokia</option>
   <option>Reliance</option>
   <option>Samsung</option>
   <option>LG</option>
</select>

<br><br>
Quantity:<input name="qty"> <br><br>

<input type="submit" name="sub" value="ADD">
</form>
</body></html>

Billing.php

<html>
<head>

<?php  
session_start();
echo session_id();
echo "<br>";
echo "selected products are:<br>";
// print_r($_SESSION);
foreach($_SESSION as $x=>$y){  
   echo "product is $x and Quantity is:$y<br>";
}
?>
</head> </html>

输出

 Warning: session_start() [function.session-start]: Cannot send session cookie - 
 headers already sent by (output started at E:\PHP programs\Billing.php:2) in   E:\PHP     programs\Billing.php on line 4

Warning: session_start() [function.session-start]: Cannot send session cache limiter - 
headers already sent (output started at E:\PHP programs\Billing.php:2) in E:\PHP programs\Billing.php on line 4

请任何人为上述警告信息提供解决方案,如何成功执行程序?

4 个答案:

答案 0 :(得分:2)

您需要在{out}输出之前放置session_start();(在文件的第一行)。 session_start需要发送一个cookie标头,如果您已向用户发送任何输出,该标头将失败。

<?php
session_start();
?>
**shopping.php**

<html>

<head>

<?php 

if(isset($_POST['sub'])){

答案 1 :(得分:2)

SESSION必须位于文件的顶部。使用session_start();启动代码。

看起来您已首先声明<html>,然后您已在billing.php开始会话,只需按照以下方式进行更改...

<强> Billing.php

<?php session_start(); ?>

<html>
<head>

答案 2 :(得分:0)

** Billing.php **

<?php
session_start();
?>
<html>
<head>

删除您生成错误的php文件中session_start之前可能有的任何新行或任何类型的输出。

答案 3 :(得分:0)

可能是你正在尝试做这样的事情......检查一下你有两个像你创建的文件。你忘了做的主要事情是你的第一个文件中的session_start()。因此$ _SESSION充当用户创建的数组变量而不是会话变量。

<?
    //you always need to start session before using the session in php
    session_start();
?>
<html>
<head>
<?php 
if(isset($_POST['sub'])){
    $a=$_POST['prod'];
    $b=$_POST['qty'];
    $_SESSION[$a]=$b;  

    // check if its being added in the session or not
    print_r($_SESSION);  
}    
?> 

</head>
<body>
<form method="post" action="">
Select any Product:
<select name="prod">
<option>Nokia</option>
<option>Reliance</option>
<option>Samsung</option>
<option>LG</option>
</select>
<br><br>
Quantity:<input name="qty"> <br><br>
<input type="submit" name="sub" value="ADD">
</form>
</body>
</html>
<? 
    //it is best way to close the session at the end of the file
    session_close();
?>


<? session_start();?>
<html>
<head><title>Billing.php file</title></head>
<body>
<?php
echo session_id();
echo "<br>";
echo "selected products are:<br>";
 print_r($_SESSION);

foreach($_SESSION as $x=>$y){
    echo "product is $x and Quantity is:$y<br>";
}
?>
</body>
</html>