1

I am looking for the correct and most secure method of POSTing to the same page without directly defining the page itself. For example not using

<form method="post" action="/mypage.php">

Despite this being a fairly basic usage of PHP, I have found multiple contradictory sources giving advice on how to do this. Currently I simply use

<form method="post" action="">

With some source suggesting (incorrectly?)

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

However after reading more into this, one recommendation suggests using htmlentities()

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

I believe this is the most correct method for sanitisation against xss exploits, but was curious is this needed if action=""

myol
  • 8,857
  • 19
  • 82
  • 143
  • 1
    If you use `action=""` and url changed on client side (#hash or `history.push()`), form will posted to new url. – Dmitry Jan 14 '15 at 10:29

1 Answers1

2

With modern HTML, just omit the action attribute entirely. HTML 5 defines that the form should then submit to the current URL. This is the simplest and least error prone option.

When you do echo user input (such as the URL) back to the browser, always use appropriate escaping for the document type you are putting it in (htmlspecialchars for HTML, json_encode for JavaScript, etc) to protect yourself from XSS.

action is an HTML attribute so it has no intrinsic defence against XSS.

PHP_SELF is:

The filename of the currently executing script, relative to the document root.

So, unless you have put characters with special meaning in HTML into one of your file or directory names, it should be safe to echo out without escaping. However: It does no harm to play it safe and treat it like any other text you want to convert to HTML and use htmlspecialchars with it. So play it safe.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335