Question

Could someone explain the difference between these two statements:

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

and

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

I am not seeing a difference in behavior.

Was it helpful?

Solution

The difference is simple.

The first piece if code doesn't prints anything.

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

So the action parameter is empty and by default browsers submit the form to the same site, what likely would be the same value htmlspecialchars($_SERVER['PHP_SELF']); returns.

If you use the second piece of code the return of htmlspecialchars($_SERVER['PHP_SELF']); would be echoed out and the browser submits the form to the same site, like above.

Example

If your site was called form.php. The first piece of code would produce:

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

The browser sees action is empty and sends the form data to the site, form.php

And the second piece would produce:

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

OTHER TIPS

The first example will output, because htmlspecialchars does not output anything, it simply returns the processed content.

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

Which will simply submit the form to the current page.

The second example will output something like

<form method="post" action="page.php"> 

Where page.php is the current script (see here).

Because a blank action submits the form to the current page, and using your echo statement will print out a route to the current page, the two will result in the same thing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top