我需要在作业中设置Cookie。当我使用字符串(即setcookie('Name', 'John', time() + 86400)
设置它们时,它可以工作,但是当使用PHP变量(即setcookie('Name', $name, time() + 86400)
)时,则未设置cookie。
我不确定自己在做什么错。我已经在页面上回显了$ name变量,它显示了出来,所以我知道这已经设置了。当我使用$_COOKIE['Name']
显示cookie时,它在收到字符串时可以工作,而在PHP variable
时则不能。
<form action="order02.php" class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input type="text" name="fname" class="textbox" autofocus
required placeholder="First name" title="first name"
maxlength="20" pattern="[A-Za-z'-]{2,20}">
</div>
<div class="formGroup">
<label> Car model:</label>
<div class="formElements">
<input type="radio" name="model" required value="Mustang">Ford Mustang<br>
<input type="radio" name="model" required value="Subaru">Subaru WRX
STI<br>
<input type="radio" name="model" required value="Corvette">Corvette<br>
</div>
</div>
<?php
$name = $_GET['fname'];
$model = $_GET['model'];
//write cookies for name and model for 1 day
setcookie('Name', $name, time() + 86400);
setcookie('Model', $model, time() + 86400);
?>
if(isset($_COOKIE['Name'])){
echo "Cookie ".$_COOKIE['Name']." is set";
}
else{
echo "<div class='pageContainer'>";
echo "<h2 class='containerText, centerText'>Failed to validate inputs";
echo "<br><br>";
echo "<a href='order01.php'><button>Go Back</button></a>";
echo "</div>";
exit();
}
答案 0 :(得分:0)
您的代码中几乎没有问题,首先,没有结束</form>
标记,其次您必须在保存order01.php
的{{1}}上提交表单,因此请尝试它将起作用
Order01.php
cookie
Order02.php
<form action="order01.php" class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input type="text" name="fname" class="textbox" autofocus
required placeholder="First name" title="first name"
maxlength="20" pattern="[A-Za-z'-]{2,20}">
</div>
<div class="formGroup">
<label> Car model:</label>
<div class="formElements">
<input type="radio" name="model" required value="Mustang">Ford Mustang<br>
<input type="radio" name="model" required value="Subaru">Subaru WRX STI<br>
<input type="radio" name="model" required value="Corvette">Corvette<br>
</div>
<input type="submit" value="submit">
</div>
</form>
?>
答案 1 :(得分:0)
不得在Cookie行(如echo,print_r()和HTML标记)之前输出
您可以在任何输出之前编写cookie代码
<?php
$name = $_GET['fname'];
$model = $_GET['model'];
//write cookies for name and model for 1 day
setcookie('Name', $name, time() + 86400);
setcookie('Model', $model, time() + 86400);
?>
<form action="order01.php" class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input type="text" name="fname" class="textbox" autofocus required placeholder="First name" title="first name" maxlength="20" pattern="[A-Za-z'-]{2,20}">
</div>
<div class="formGroup">
<label> Car model:</label>
<div class="formElements">
<input type="radio" name="model" required value="Mustang">Ford Mustang<br>
<input type="radio" name="model" required value="Subaru">Subaru WRX STI<br>
<input type="radio" name="model" required value="Corvette">Corvette<br>
</div>
<input type="submit" value="submit">
</div>
</form>