Sasindu H
Sasindu H

Reputation: 1578

php form action php self

I have a php form like this.

<form name="form1" id="mainForm" method="post"enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">

</form

In form action I want to use page name with parameters. like house.php?p_id=10111 . But $_SERVER['PHP_SELF'] gives only the house.php (My page full url is house.php?p_id=10111 like this) Please help me to solve this problem. thanks.

Upvotes: 30

Views: 179270

Answers (8)

CryptoRhino
CryptoRhino

Reputation: 27

The easiest way to do it is leaving action blank action="" or omitting it completely from the form tag, however it is bad practice (if at all you care about it).

Incase you do care about it, the best you can do is:

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo($_SERVER['PHP_SELF'] . http_build_query($_GET));?>">

The best thing about using this is that even arrays are converted so no need to do anything else for any kind of data.

Upvotes: 1

gleb
gleb

Reputation: 59

If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Upvotes: 0

Lakshman Kambam
Lakshman Kambam

Reputation: 1618

This is Perfect. try this one :)

<form name="test" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
/* Html Input Fields */
</form>  

Upvotes: 4

Arda
Arda

Reputation: 6946

Another (and in my opinion proper) method is use the __FILE__ constant if you don't like to rely on $_SERVER variables.

$parts = explode(DIRECTORY_SEPARATOR, __FILE__);
$fileName = end($parts);
echo $fileName;

About magic and predefined constants: 1, 2.

Upvotes: 2

shaggy
shaggy

Reputation: 1718

You can leave action blank or use this code:

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI'];?>">
</form>

Upvotes: 16

joskah
joskah

Reputation: 73

You can use an echo shortcut also instead of typing out "echo blah;" as shown below:

<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">

Upvotes: 7

Shef
Shef

Reputation: 45599

How about leaving it empty, what is wrong with that?

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="">

</form>

Also, you can omit the action attribute and it will work as expected.

Upvotes: 81

Matt R. Wilson
Matt R. Wilson

Reputation: 7575

Leaving the action value blank will cause the form to post back to itself.

Upvotes: 9

Related Questions