Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use $_SERVER['PHP_SELF'] instead of ""

Tags:

forms

php

In a form on a PHP page, you can use:

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

or

<form action="#" ...> 

or

<form action="" ...> 

in the action attribute of the form. Since echo $_SERVER['PHP_SELF'] does not pass variables for using GET and you have to use "", why would you use that or "#"?

I'm asking because it took me some time to figure out that the variables are not passed with $_SERVER['PHP_SELF']. Thanks.

like image 228
robk27 Avatar asked Dec 30 '12 18:12

robk27


People also ask

What is the use of $_ SERVER PHP_SELF?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script. So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.

What does PHP_SELF mean?

PHP_SELF is a variable that returns the current script being executed. You can use this variable in the action field of the form. The action field of the form instructs where to submit the form data when the user presses the submit button. Most PHP pages maintain data validation on the same page as the form itself.

What is the $_ SERVER PHP_SELF variable explain with example?

$_SERVER['PHP_SELF'] variable. This array element points out the filename of the currently executing script. For example, if you run www.cyberciti.biz/index.php, $_SERVER['PHP_SELF'] would be /index.

What is the usage of $_ SERVER [' Server_addr ']?

The $_SERVER['SERVER_ADDR'] returns the IP address (Internet Protocol address) of the host server. Following php code used $_SERVER['SERVER_ADDR'] to display the IP address of the host server.


2 Answers

The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".

There is no reason to use $_SERVER['PHP_SELF'], and # doesn't submit the form at all (unless there is a submit event handler attached that handles the submission).

like image 94
Niet the Dark Absol Avatar answered Oct 11 '22 18:10

Niet the Dark Absol


Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF'].

When using $_SERVER['PHP_SELF'] it is very easy to inject malicious data by simply appending /<script>... after the whatever.php part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.

like image 26
ThiefMaster Avatar answered Oct 11 '22 17:10

ThiefMaster