开发者

Simple PHP cookie question

开发者 https://www.devze.com 2023-02-06 16:48 出处:网络
Why wont this work? Below code is on send.php <?php $expire=time()+60*60*24*30; $name = $_POST[\'nameField\']开发者_运维百科;

Why wont this work?

Below code is on send.php

<?php
  $expire=time()+60*60*24*30;
  $name = $_POST['nameField']开发者_运维百科;
  setcookie("name", $name, $expire);
?>

The cookie's value is blank. Why? How do I fix this?

New question:

Why is $_POST['nameField'] NULL?

<form action="/contact/send.php" method="post" id="contactForm">
<input type="text" id="nameField" name="Name" value="<?php if (isset($_COOKIE["name"])){ echo $_COOKIE["name"];} ?>" class="extra_large" />
<input type="submit" class="submit" name="Submit" value="   Send   " />


<input type="text" id="nameField" name="Name"

This input's name must be nameField , too.

<input type="text" id="nameField" name="nameField"

$_GET and $_POST variables gets value of form input's , by name. For example $_GET['stack'] and $_POST['stack'] gets <input name="stack">'s value.


In the HTML you should write name="nameField", name is the name for posted value not id, if so, the code above seems to be working correctly


The name of the form field is 'Name', the id is 'nameField'. You therefore need to use either

$name = $_POST['Name'];

or change the name on the input to nameField


About the cookie: Cookies will only take effect on the next page load. So if you set a cookie, you can not reference or use the cookie until you load another page. It's just one of the quirks of how they work.

About the POST: You need to use $_POST['name_attribute'] instead of the ID


How do you know it isn't working?

Cookies (and so $_COOKIE) won't be set until the next page load - it has to return the header that sets the cookie to the client before the client will send its request with the cookie in it.

Thus there will be an HTTP request for this script, it will return headers to set the name cookie along with any output, and will only be the next page that will get (and populate $_COOKIE) with the name cookie.

In addition, as noted, $_POST[] references the name attribute of a form element. Your textbox needs to have name='nameField', not just id.

0

精彩评论

暂无评论...
验证码 换一张
取 消