Monday, May 30, 2011

PHP User System: Inserting new users

We will be walking through very quickly to show you how to implement a simple user system. We are not focused on security in this blog posting, however if you do have questions about making the script more secure email us or head over to hackhound.org and ask someone to help you.

You can get a copy of the users database we are using from our previous post here. If you don't know how to do it, refer to a MySQL tutorial, not a PHP tutorial. We are covering how to interface with MySQL, not how to build a MySQL database, sorry :/

Registration
When you implement user registration keep in mind that you can only get as much user info as your user table can hold, unfortunately we are left with a rather small users table to deal with. Some user tables can have as many as 30 fields, insane..

login.php
<form method="post" action="register.php">
    <p>username<br/>
    <input type="text" name="username">
    </p>

    <p>email<br/>
    <input type="text" name="email">
    </p>

    <p>password<br/>
    <input type="password" name="password">
    </p>

    <p><input type="submit" value="register user"></p>
</form>
 login.php will send the data to our register.php script.

register.php
<?php
mysql_connect("127.0.0.1","root","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$username = $_POST['username'];
$password = md5($_POST['password']);
$email = $_POST['email'];

mysql_query("insert into users value('','$username','$password','$email')") or die(mysql_error());

echo "user registered";
?>
 You would probably want to make sure they verify their email, but that's a bit advanced for you right now. I also did not clean the inputs, please do not use this on your own website, this is for development purposes/learning purposes only. You will also want to check if the user or email already exists, but like I said, this is pretty much bare bones development stuff.

Once registered you can let the user login using a login form, login.html

login.html
<form method="post" action="login.php">
<p>username<br/>
<input type="text" name="username">
</p>

<p>password<br/>
<input type="password" name="password">
</p>

<p><input type="submit" value="log me in">
</p>
</form>

login.php
<?php
mysql_connect("127.0.0.1","root","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$username = $_POST['username'];
$password = md5($_POST['password']);

$q = mysql_query("select * from users where username = '$username' and password = '$password'");
$g = mysql_fetch_array($q);

print_r($g);
?>
Once logged in you will want to start a session to carry the user from page to page.

No comments:

Post a Comment