Question

I just realise that, for some weird circumstances, I was doing what I believe to be self submissions, without any reference to PHP_SELF on the action form attribute.

I'm puzzled, can we either use

<?php echo filter_var($_SERVER['PHP_SELF'], FILTER_SANITIZE_STRING); ?>

Or

action="" 

?

If not, on what circumstances should we considered one, or another?

Thanks in advance, MEM

Was it helpful?

Solution

You can use either (PHP_SELF or empty string). but why would you use FILTER_SANITIZE_STRING for this? You'd better to use htmlentities() instead of filter_var in this case, if your path contains filtered characters (e.g. <), the form won't submit.

I prefer giving a string, <base href=> can cause trouble when using empty values. Example:

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

OTHER TIPS

If I'm not mistaken Safari had/has problems with the latter, therefore I dropped using it.

Please do not use PHP_SELF, because this can also be /index.php/"><script>alert(1)</script>/.

It's often used for XSS Attacks.

Use the index SCRIPT_NAME instead! SCRIPT_NAME will always point to the actual PHP file and not to the user-input.

Regards

Edit:

Two people point out, that SCRIPT_NAME would not work when using mod_rewrite. This is false and I think these people should read before they vote answers down.

Here's a test scenario for you ***:

$ cat .htaccess 
RewriteEngine On
RewriteRule testme/ /testmenot.php

$ cat testmenot.php 
<? echo $_SERVER['SCRIPT_NAME']; ?>

$ GET hostname/testme/
/testmenot.php

$_SERVER['REQUEST_URI'] is holding "/testme/", which i guess these people would have expected in SCRIPT_NAME. But that can also not be found in PHP_SELF.

/me crosses fingers
:E

     <?php
     session_start();
        $msg = '';

        if (isset($_POST['login']) && !empty($_POST['username']) 
           && !empty($_POST['password'])) {

           if ($_POST['username'] == 'abc' && 
              $_POST['password'] == 'xyz') {
              $_SESSION['valid'] = true;
              $_SESSION['timeout'] = time();
              $_SESSION['username'] = 'abc';
              ?>

              <script type="text/javascript">

          location.href="index.php"

        </script>
              <?php 
           }
           else 
           {
              $msg ='Invalid username or password';
           }
        }
     ?>
       <form
        action ="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); 
        ?>" method = "post">
              <input type = "text" class = "form-control" 
           name = "username" placeholder = "username" 
           required autofocus ></br> 
          <input type = "password" class = "form-control"
           name = "password" placeholder = "password" required>

      <input class="button" type = "submit"  name = "login" value="Log in"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top