简体   繁体   中英

Retaining Form Values

How can we retain form values? The Server is written in PHP, and the action for the form is "echo $_SERVER[PHP_SELF]".

Without the use of cookies, PHP sessions, and without binding PHP variables to HTML Form values; how can we possibly retain form values?

  • The simplest way with only HTML code is by adding the autocomplete="on" attribute to your form element.
  • The best way is via embedding the PHP vars in the form. Try receiving/capturing the form values via the $_POST / $_GET super-globals. eg:

 // HTML <form name="foo" action="<?php echo $_SERVER[PHP_SELF] ?>" method="POST"> <input type="text" name="username" placeholder="Enter username" value="<?php echo $username ?>" /> <input type="password" name="password" placeholder="Enter password" value="<?php echo $password ?>" /> <button type="submit">Submit</button> </form> // PHP $username = !empty($_POST['username']) ? $_POST['username'] : ''; $password = !empty($_POST['password']) ? $_POST['password'] : ''; echo $username . $password; 

On submit just create a cookie witch contain all the data and if signIn or signUp is successful then unset the cookie but if error occurs then use that cookie and show data.

Create cookie for form

setcookie('form_data', $_POST, time() + (86400 * 30), "/");

If error occurs store cookie in variable and use in form

$data = $_COOKIE['form_data'];

Display in form

<Input type='text' value='<?= isset($data['username'])?$data['username']:'' ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM