<? php echo $_SERVER["PHP_SELF"];? > what is the function?

Asked

Viewed 4,917 times

4

I was studying about POST methods and all right, I know that the form needs to process and so it is forwarded via action, but what is the function of the code:

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

this $_SERVER["PHP_SELF"] reflects the very page on the server to perform the "processing" is this?

<html lang="en">
<head>
    <title>Example of PHP POST method</title>
</head>
<body>
<?php
if(isset($_POST["name"])){
    echo "<p>Hi, " . $_POST["name"] . "</p>";
}
?>
**<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"**
    <label for="inputName">Name:</label>
    <input type="text" name="name" id="inputName">
    <input type="submit" value="Submit">
</form>
</body>

1 answer

3


Yes, $_SERVER["PHP_SELF"] is the path to the file itself in question. This way, when submitting the form, the POST request will be sent to itself. However, it is not recommended that you do this.

If your file has the name cadastro.php, when accessing, for example, /cadastro.php, the form in HTML will be:

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

It seems all right, but this opens up some loopholes in your application. Someone with bad intentions could very well access the URL

/cadastro.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E

Depending on how your server is configured and, mainly, if you did not properly handle all user inputs, your HTML would be:

<form method="post" action="cadastro.php">
<script>alert('xss')</script>

That is, you would allow the user to add one script JS on your page, which features an XSS attack if you want to read more.

Another point is that ideally the response to a POST request should contain the header Location to redirect the user. The way you did, the user will see the same screen, with the form, with the message "Hi Fulano". If the user refreshes this page, the browser will ask if they want to resend the information. In this case there will be no side effect, but imagine that this is a contact form; each time the user updated the page a different email would be sent.

So, ideally, the POST request response has the header Location to a URL representing the resource created. In the redirect, the browser will perform a GET request on the given URL, removing the problem of forwarding the form information, and the user can update the page freely.

Of course, every case is a case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.