Hi,
You could just use
Code: Select all
$_SESSION['username'] = $_POST['username'];
instead, but the username that someone has supplied you with might not be safe so (normally) you would want to truncate the value to a specific length (the maximum allowed field length of the username in the database) and then use functions such as trim(), strip_tags(), htmlentities() or other similar functions. The issue is that you would expect someone to enter a username like
johndoe1
but someone might instead enter something like
javascript:alert('Hello World!');
' OR 1'
; SELECT * FROM users WHERE 1;
or a series of UTF-8 codes that do unexpected things. This also applies to the password field as well.
The way I store username and password fields in my database is to use a one-way hashing function such as sha1() which will take a username and password such as
johndoe1
topsecretpassword
and convert it to
7a86a8cf9d7510cc4661b217133f2eed37981b75
1291e042ae17ff1bb62db330064287cbe9b728bf
Note that my implementation is more complex than this and I'm just using a simple example so you can understand how it works.
When you receive the username and password from your login form, you run the values through the same function and then match against the converted versions instead, so your query looks something like
Code: Select all
$sql = mysql_query("SELECT * FROM users WHERE username_hashed = '7a86a8cf9d7510cc4661b217133f2eed37981b75' AND password_hashed = '1291e042ae17ff1bb62db330064287cbe9b728bf'");
Note that you would still want to store a copy of the username as it normally appears, but you don't need to (and shouldn't) do this for the password.
The issue is more complicated for passwords, because if someone knows the converted value and the hashing function used they could run their own script to try and guess what the password was (they would need a copy of the record in the database though). As previously discussed, storing passwords safely in a database is a complex issue and many web sites get it wrong, even very big sites. So it is something that you will need to spend some time learning about if you want to create safe and secure login scripts. This topic is frequently covered on this forum in the "Security" section, so there are lots of posts available that cover the main issues and provide good code examples. Another issue that you need to consider is how to stop people trying hundreds or thousands of combinations of username/password combinations.
HTH,
M_G