Is it a good practice to use an empty URL for a HTML form's action attribute? (action=“”)

后端 未结 11 2197
花落未央
花落未央 2020-11-22 01:50

I am wondering if anyone can give a \"best practices\" response to using blank HTML form actions to post back to the current page.

There is a post asking what a blan

相关标签:
11条回答
  • 2020-11-22 02:19

    Not including the action attribute opens the page up to iframe clickjacking attacks, which involve a few simple steps:

    • An attacker wraps your page in an iframe
    • The iframe URL includes a query param with the same name as a form field
    • When the form is submitted, the query value is inserted into the database
    • The user's identifying information (email, address, etc) has been compromised

    References

    • Bypassing CSRF protections with ClickJacking and HTTP Parameter Pollution
    0 讨论(0)
  • 2020-11-22 02:20

    The best thing you can do is leave out the action attribute altogether. If you leave it out, the form will be submitted to the document's address, i.e. the same page.

    It is also possible to leave it empty, and any browser implementing HTML's form submission algorithm will treat it as equivalent to the document's address, which it does mainly because that's how browsers currently work:

    8. Let action be the submitter element's action.

    9. If action is the empty string, let action be the document's address.

    Note: This step is a willful violation of RFC 3986, which would require base URL processing here. This violation is motivated by a desire for compatibility with legacy content. [RFC3986]

    This definitely works in all current browsers, but may not work as expected in some older browsers ("browsers do weird things with an empty action="" attribute"), which is why the spec strongly discourages authors from leaving it empty:

    The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

    0 讨论(0)
  • 2020-11-22 02:28

    IN HTML 5 action="" IS NOT SUPPORTED SO DON'T DO THIS. BAD PRACTICE.

    If instead you completely negate action altogether it will submit to the same page by default, I believe this is the best practice:

    <form>This will submit to the current page</form>
    

    If you are sumbitting the form using php you may want to consider the following. read more about it here.

    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    

    Alternatively you could use # bear in mind though that this will act like an anchor and scroll to the top of the page.

    <form action="#">
    
    0 讨论(0)
  • 2020-11-22 02:33

    I normally use action="", which is XHTML valid and retains the GET data in the URL.

    0 讨论(0)
  • 2020-11-22 02:37

    This will validate with HTML5.

    <form action="#">
    
    0 讨论(0)
提交回复
热议问题