ds211107 2011-07-27 02:09
浏览 91
已采纳

如何在重定向回提交表单的页面时标记PHP中缺少的字段?

I have a form in the footer of my website that appears on each page. I need to make it so if a user submits the form with blank fields, it will flag the error message in the form. It currently directs them to a different page where there data is submitted to another server. I'm already using JavaScript for this, but need to add an additional validation layer with server-side code.

I know how to detect if the form fields are empty, but how can I use server-side code to redirect back to the referring page and include some parameters that can be used in the footer to detect which fields were empty?

I'm assuming I'd have to use PHP's header() with the http_referer, but how can I pass the parameters back to that page without anything showing up in the URL?

  • 写回答

2条回答 默认 最新

  • douluan1533 2011-07-27 02:14
    关注

    Keep a record in $_SESSION of the invalid/empty fields and flag them with CSS in your form:

    session_start();
    
    // When you begin validating your form, clear out any old fields from $_SESSION
    $_SESSION['previous'] = array();
    $_SESSION['invalid'] = array();
    
    // when you encounter an empty or invalid field,
    // add it to an array in $_SESSION
    $_SESSION['invalid']['fieldname'] = TRUE;
    
    // Store the previous POST value too
    $_SESSION['previous']['fieldname'] = $_POST['fieldname'];
    

    In your form, you can check if there's an invalid field and add a CSS class to indicate invalidity. This sets the class invalid:

    <input name='fieldname' type='text'
      class='<?php if (isset($_SESSION['invalid']['fieldname'])) echo "invalid";?>' 
      value='<?php if (isset($_SESSION['previous']['fieldname'])) echo htmlentities($_SESSION['previous']['fieldname'], ENT_QUOTES); ?>'
    />
    

    Do this for all your form fields. Use the same method to retain the previous $_POST values and echo them out into the field's value attribute.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改