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条)

报告相同问题?

悬赏问题

  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error