简体   繁体   中英

How to design user input form in php

I am developing website for a company in php . In website, im making user input form. I just want to know is it good to write logic and html code in one php file or not. when i use seperate pages.. one for html code and another php logic. I faced problem in validating form . I am validating form using both ways ie javascript and php. javascript is ok. but for php.. validation is little bit difficult. when errors occures, how it goes to html page to show errors after validating on server side?

It makes sense to keep HTML and logic separate where possible. Displaying errors can be accomplished using session data. For instance:

form.php:

<form method="post" action="submit.php">
  <input type="text" name="email">
  <?php if(isset($_SESSION['form']['error']['email'])){ ?>
    <b>Error:</b> <?=html($_SESSION['form']['error']['email'])?>
  <?php } ?>
  <button type="submit">Go</button>
</form>
<?php unset($_SESSION['form']['error']);

submit.php:

<?php
  if($_POST['email'] == ''){
    $_SESSION['form']['error']['email'] = 'Email is required';
  }
  if(!empty($_SESSION['form']['error'])){
    // There was an error
    header('Location: form.php');
    die;
  }
  // No errors, handle the data, then redirect user to success.php:
  header('Location: success.php');

Remember to require a config file before loading these pages:

config.php

<?php
  session_start();
  function html($str){
    return htmlspecialchars($str, ENT_QUOTES);
  }

Note that this is a simplified example, and you should use functions to make the $_SESSION code more accessible.

Another benefit of separating HTML and logic is that the user will not be asked if they would like to resubmit the form when reloading the form.

For javascript validations, you can use alert() provided in javascript to show error in the same page but if you want to show error generated on php validations then you can use redirect with error variable ie

header("location:filldetails.php?error=".$error); 

where your-url.com is the page address in your project

error is the variable name through which u can get the generated error

some_error is the generated error

Now, after sending error to the previous page, its to get it

if(isset($_GET['error']))
{
   echo $_GET['error'];
}

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