How do many of the websites that have logins keep the username in the username field when the password is entered incorrectly. The form's action (it is on index.php) is another php file, which if the password is incorrect uses Header() to go back to the index and passes the error to it using GET. I could use GET to pass the username back to the form but this seems messy, and I have noticed that websites like SMF forums have the username stay in the username field without a messy URL.
+3
A:
I normally find it easier to process form data in the same script where the form is displayed and redirect somewhere else only when I've gathered correct input.
Álvaro G. Vicario
2010-04-12 09:37:54
+1
A:
You can use sessions.
For example, when a post is incorrect (this would go in the file processing your post request):
$_SESSION['username'] = $_POST['username'];
Then on your login page:
<input type="text" name="username" value="<?php echo @$_SESSION['username']; ?>" />
Make sure you start the session though: http://php.net/session_start
Andrei Serdeliuc
2010-04-12 09:38:27
As a general rule, I wouldn't recommend using sessions for this kind of purposes: you end up with sites that break when the user opens several tabs.
Álvaro G. Vicario
2010-04-12 10:08:01
Sessions are carried across tabs / windows. I do agree that dealing with forms is easier if the form posts to itself, but this isn't always the case. How would you carry user data across different pages on failed validation if not with sessions? (Granted that you have to be careful to empty session data between requests after the data has been displayed, etc.)
Andrei Serdeliuc
2010-04-12 10:58:08
I can't think of any issue in the current context. I warn against the policy of using sessions as a general replacement for forms (a very popular technique in some areas such as booking sites).
Álvaro G. Vicario
2010-04-12 12:25:15
A:
Through GET method
header("Location: loginpage.php?username=".$_REQUEST['username']);
and in form page u can access it like:
<input type="text" name="username" value=<?php echo $_GET['username']?>
nik
2010-04-12 09:42:18
Quote from the question: "I could use GET to pass the username back to the form but this seems messy"
Jonathan
2010-04-12 09:59:13
How would you be open to SQl injections, nothing is getting submitted to the database?
Jonathan
2010-04-12 10:00:07
ok! Johnathan, If u dont wanna get Method (Rightfully). You can do it from sessions, or call login script thru Ajax, Or with the help of hidden variable u don't even have to go to other page rather than index.
nik
2010-04-12 10:52:15
A:
Simples!
<form action="loginpage.php" method="post">
<fieldset>
...
<input type="text" name="username" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" />
...
</fieldset>
</form>
Rest of the form ommitted to emphasize solution.
Martin Bean
2010-04-12 09:57:57
but how do I get the username into the POST variable from the login.php?
Jonathan
2010-04-12 10:01:04