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

报告相同问题?