0

I wrote a login code in PHP:

<form NAME="form1" METHOD="POST" ACTION="operation/validateLogin.php">
        Username <br/><input name="username" type=text autocomplete="off"><br/><br/>
        Password <br/><input name="password" type=text autocomplete="off"><br/><br/>
        <button class="btn btn-primary submit" type="submit">Sign In</button>
</form>

When I submit the form the credentials are sent to a validation file. If an error occurs the file sends the error message back to the login page:

header("Location: http://localhost/demoapp/login.php/?em=28");

I handle the 'GET' parameter and print the error message:

if (isset($_GET['em'])){
        if($_GET['em'] == 28){$errorMessage = "Your username or password was incorrect.";}
}

Now the user needs to try to login again by resubmitting the form, but the action of the form is:

operation/validateLogin.php

and the URL is now:

http://localhost/demoapp/login.php/?em=28

Therefore, when the form is submitted the url becomes:

http://localhost/demoapp/login.php/operation/validateLogin.php

When it should be...

http://localhost/demoapp/operation/validateLogin.php

How do you prevent this from happening to the URL?

1 Answers1

0

The ACTION attribute of an HTML form can be set with a relative URL:

/operation/validateLogin.php

or

/validateLogin.php

It's actually recommended to work with relative URLs for HTML elements: Absolute vs relative URLs

However, when working with PHP an absolute URL is your best option:

http://localhost/demoAPP/operation/validateLogin.php

The use of absolute URLs will relieve your code of accidental URL concatenation.

I had trouble recently figuring out which type of URL to use for certain situations, but this is what I've realized...

PHP (local/server language) = Absolute Local/Server Address

require "C:/dev/www/DEMO/operation/login/validateLogin.php";
include "C:/dev/www/DEMO/operation/login/validateLogin.php";
header("Location: http://localhost/demoapp/login.php/?em=28"); (redirect to a web address)

This may seem really simple but remembering this will save you a lot of troubleshooting time.

If you are using .PHP files, alter the URL in any way, and are not using absolute URLs you will most certainly receive errors.


Additional: You'll notice that you can use a web address for HTML attributes and not run into any problems. However, with PHP requires and includes you can only use local addresses. There is a reason for this limitation and it's all because of one important PHP setting...

https://help.dreamhost.com/hc/en-us/articles/214205688-allow-url-include

Community
  • 1
  • 1