【发布时间】:2016-01-27 20:12:52
【问题描述】:
大家好,我是 php 的初学者,我正在学习 cookie,我现在正在学习一个教程,但我在调试这个练习时遇到了问题,它只是假设存储一个名称和位置 cookie。
这是我的 php 脚本
<?php
/**
* In this example, you create a script that can store the visitor’s first name and location in two browser cookies,
* retrieve and display the information from the cookies, and delete the cookies on request.
**/
define('URL', 'https://collabbro-bvcxtds.c9.io/app/php-practice/remember-me.php');
if (isset($_POST['sendInfo'])) {
storeInfo();
} elseif (isset($_GET['action']) and $_GET['action'] == 'forget'){
forgetInfo();
} else {
displayPage();
}
function storeInfo() {
if (isset($_POST['firstName'])) {
setcookie('firstName', $_POST['firstName'], time() + 60 * 60 * 24 * 365, '', '', false, true);
}
if (isset($_POST['location'])) {
setcookie('location', $_POST['location'], time() + 60 * 60 * 24 * 365, '', '', false, true);
}
header('Location:' . URL);
}
function forgetInfo() {
setcookie( 'firstName', '', time() - 3600, '', '', false, true);
setcookie( 'location', '', time() - 3600, '', '', false, true);
header('Location:' . URL);
}
function displayPage() {
$firstName = (isset($_COOKIE['firstName'])) ? $_COOKIE['firstName'] : '';
$location = (isset($_COOKIE['location'])) ? $_COOKIE['location'] : '';
}
?>
这是我的html
<!DOCTYPE html>
<html>
<head>
<title>Remeber me user information with cookies</title>
</head>
<body class="homepage">
<!-- nav -->
<!-- end nav -->
<h1>Remember User infomration with cookies</h1>
<?php if ($firstName or $location) { ?>
<?php echo '<pre>'; var_dump($firstName); exit(); ?>
<?php echo '<pre>'; var_dump($location); exit(); ?>
<p>Hey, <?php echo $firstName ? $firstName : 'visitor' ?> <?php echo $location ? 'in $location' : '' ?>! </p>
<p>Here's a little nursery rhyme I know:</p>
<p><em>Hey diddle diddle, <br>
The cat played the fiddle <br>
the cow jumped over the moon <br>
the little dog laughed to see such sport <br>
and the dish ran away with the spoon </em></p>
<p><a href="<?php URL ?>?action=forget">Forget about me</a></p>
<?php } else { ?>
<form action="<?php URL ?>" method="post">
<input type="text" name="firstName" id="firstName" placeholder="please enter your first name"/>
<input type="text" name="location" id="location" placeholder="Where do you live?"/>
<input type="submit" value="Submit" name="sendInfo" id="sendInfo"/>
</form>
<?php } ?>
<!-- footer -->
<!-- end footer -->
</body>
</html>
这是我的调试步骤
我要做的第一件事是 vardump() $firstName & $location 在我的条件语句中 <?php if ($firstName or $location) { ?>
这没有给我任何东西,所以我检查了我的 post 方法,看看它是否发送回页面(据我所知)
但是看看我处理输入的代码一切看起来都不错,不知道发生了什么,感谢您的帮助!
【问题讨论】:
-
一个可能的问题是按钮并不总是发送它们的值。最好检查 if(isset($_POST['firstName'])) 以保存 cookie。调试的下一步是设置 $dummy = true;在 PHP 的顶部,然后在 HTML 中的 if($dummy) { die('It working');} 以查看该脚本中的变量是否可以在 HTML 模板中访问。
-
@Cuagau 我尝试测试
$_POST['firstName] 并且它有效。但仍然没有渲染任何东西