我是第一次测试PHP cookie,根据W3Schools教程,我认为我做的一切正常,但我的cookie的价值一无所获。
这是我的整个表单验证代码,cookie代码位于process.php中:
function validate_post_form() {
global $postMsg;
$valid = true;
if ( $_POST['course'] == null || $_POST['course'] == "") {
$postMsg .= " You must choose a course.";
$valid = false;
}
if ( $_POST['convert'] == null || $_POST['convert'] == "") {
$postMsg .= " You must choose to convert the text or not.";
$valid = false;
}
if ( $_POST['input'] == null || $_POST['input'] == "") {
$postMsg .= " You must enter an text input to process.";
$valid = false;
}
$set = $_POST['set'];
// check if cookies or session radio button is set
if ($set == "cookie") {
$value = "<img src=\"../BENSON_Cookies/PleaseNoDeleteMyCookies.JPG\" />";
$cookie = setcookie("Cookie", $value, time()+3600);
} else if ($set == "session") {
echo "You have selected session.";
}
if ($cookie) {
echo "The cookie is set.";
} else {
echo "The cookie is not set.";
}
echo $postMsg;
return $valid;
} // End validate_post_form() function
这是我在index.php页面上的表单代码:
<form action="process.php" method="post" target="preview">
Set: <input type="radio" name="set" value="cookie">Cookies
<input type="radio" name="set" value="session">Session<br>
<span style="color:red;">*</span>Course:
<select name="course" class="form-control">
<option value="">Choose:</option>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="PHP">PHP</option>
<option value="JavaScript">JavaScript</option>
</select><br>
<span style="color:red;">*</span>Convert Text?
<input type="radio" name="convert" value="Yes">Yes
<input type="radio" name="convert" value="No">No<br>
<span style="color:red;">*</span>Text Input:<br>
<textarea class="form-control" name="input" placeholder="Input text here."></textarea><br>
<button class="btn btn-default" type="submit">Submit</button>
</form>
正如您从表单代码中看到的那样,process.php页面正被发送到目标iframe命名预览。如果选择了cookie,那么我希望它设置cookie,并打印cookie的值,这是cookie怪物的图片。
新输出是:
The cookie is not set.
答案 0 :(得分:2)
You cannot see the cookie set until the script executes and then if you put
the println in the next page , you should be able to see it.
Here is the setcookie example :
$cookiename ='mycookie';
$value="mytestvalue";
$expiry=time()+3600;
$path="/";
$domain="my.domain.name";
$secure=true;
$httponly=true;
setcookie($cookiename,$value,$expiry,$path,$domain,$secure,$httponly);
Use the following to access the cookie :
$mycookie = $_COOKIE["mycookie"];
Another easier way to check the cookies is to use the firebug tool on
firefox or plugins like editthiscookie on chrome.
答案 1 :(得分:1)
对我来说,它似乎没有获得$ _POST [&#39; set&#39;]变量权限,因此它不会执行Cookie代码。我认为问题是你没有关闭你的输入标签,你的浏览器现在正在疯狂。尝试关闭它,看看会发生什么。