phphtmlwordpressformsserver

$_SERVER['SCRIPT_NAME'] and $_SERVER['PHP_SELF'] returns index.php although the script is run on other page(s)


I am building an HTML form with PHP validation inside WordPress. Initially I built it on index.php and had no issues. But upon moving the form to another page (/form.php) the problem arise, since I want the form to be run and error handled on the same page (equivalent to action="").

I have tried with $_SERVER['PHP_SELF']:

<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
    <input name="test">
    <button type="submit" name="submit">Send</button>
</form>

with $_SERVER['SCRIPT_NAME']:

<form method="POST" action="<?php echo htmlspecialchars($_SERVER['SCRIPT_NAME']); ?>">
    <input name="test">
    <button type="submit" name="submit">Send</button>
</form>

and with $_SERVER['SCRIPT_FILENAME']:

<form method="POST" action="<?php echo htmlspecialchars($_SERVER['SCRIPT_FILENAME']); ?>">
    <input name="test">
    <button type="submit" name="submit">Send</button>
</form>

but the form directs me to index.php although form.php (or the like) is excepted.

When checking the output of var_dump($_SERVER) on the page, these values are outputed on the screen:

["PHP_SELF"]=> string(24) "/root-folder-name/index.php"
["SCRIPT_NAME"]=> string(24) "/root-folder-name/index.php"
["SCRIPT_FILENAME"]=> string(40) "[...]/root-folder-name/index.php"

What am I missing?


This one returns the path of the current document:
["REQUEST_URI"]=> string(20) "/root-folder-name/form/".


Solution

  • You can try using the get_permalink() function.

    <form method="POST" action="<?php echo esc_url(get_permalink()); ?>">
        <!-- Form fields -->
    </form>