Just a general question. In terms of form actions if the form is submitting to it’s parent page I realize that you can use “” or “#” to submit the form. Now my question is when writing a php page that has both the handler and the form I was told it was best to write a form action like this:
action="<?php echo $_SERVER['PHP_SELF'] ?>"
//or
action="<?php echo $_SERVER['SCRIPT_NAME'] ?>"
Now why would you need to add this inline script if you could have the form submit to itself using ‘#’ or just simply not setting the form action. I’m just curious, as adding in that php does create bulky and messy looking form code (which is already bulky and messy looking).
I also understand that the alternate ‘#’ and “” could be used in cases that you aren’t using PHP, but I guess the real question is why add the PHP if you don’t need it (in instances that the form is submitting to a php page).
thanks,
Brodie
Mahalo guys for all the responses. I realize that using the PHP code to generate the url is probably (in most cases) the route to take, as all it would take is for an update to a browser or to HTML in general to say “” and “#” are invalid operators for submitting to the root page. Also I know that the ‘#’ is for referencing an anchor on the same page, but I figured I’d see what everyone’s take on it was.
First of all the easy part: why put something into the value of
actionin the first place.Well, the HTML 4 spec says (emphasis mine):
Therefore, while practically all browsers will end up submitting the form to the script itself, technically this is a happy coincidence that you should totally not rely on. However, this is not a problem for HTML 5.
In addition,
#by itself is not a valid URI as per the W3C’s definition, so that should be ruled out as invalid as well.Now for the other half: how to get the current URL in PHP.
For basic usage, you can use either one of
$_SERVER['REQUEST_URI']and$_SERVER['PHP_SELF']for this, depending on if you want to preserve any GET parameters in your current URL (PHP_SELFwill not include them, butREQUEST_URIwill).In more advanced scenarios (e.g. writing code using a framework) it would be better to use the framework’s own URL-generating utility functions to generate the URL for you (this would take routing etc into account, so is preferable).
Update: I misread the HTML 5 spec, which says you can leave the action blank.