(PHP) Is handling a form submission on the same page more/less/equally good as handling on a separate page?

后端 未结 3 1919
耶瑟儿~
耶瑟儿~ 2021-01-13 20:23

I have a PHP form, and I\'m wondering how I should handle submission. I remember when learning Rails that the behavior was to have a special handler page for a form, which t

相关标签:
3条回答
  • 2021-01-13 21:13

    Post-Redirect-Get is the design pattern recommended for web-forms to prevent resubmission (and what you used in rails)

    It doesn't really matter if you submit to the same page or a different one, it's the redirect which prevents the accidental resubmission. You can therefore choose whether to post to the same page or a separate page depending on your coding style and/or application semantics.

    0 讨论(0)
  • 2021-01-13 21:13

    The same principles apply to PHP. Redirection can help against accidental form refreshing. However, you still should take whatever precautions are necessary to avoid problems from accidental refreshing (e.g., using single use tokens, validating the input, etc).

    I use my own MVC style of framework that simply has the dispatcher look for form posts on every page view and calls the appropriate controller that can process the request (assuming the submit-only-once requirements were met). It then redirects the browser to the appropriate landing page.

    You can post to the same page, of course, but I think it will lead to bad practices, such as mixing too much logic, html, and database access together.

    0 讨论(0)
  • 2021-01-13 21:18

    There's a third way to go about this that I am particularly fond of. In an effort to separate logic from presentation, I like to include a PHP file with every HTML document that requires processing of some kind (such as displaying dynamic data, handling HTTP POST requests etc.). I generally store this file in a separate directory and name it "filename.page.php". Needless to say, this is nothing more than a coding convention and you may want to call it something else.

    In a sense, this means you're handling the HTTP POST request in the same file (at least as far as your web server is concerned). You can redirect clients anyway, though, by using the HTTP Location header like so:

    header("Location: file.php")

    As a side note, I wouldn't depend upon HTTP POST for security; it is no harder to make arbitrary HTTP POST requests than HTTP GET requests.

    0 讨论(0)
提交回复
热议问题