Stick Page Forums Archive

Creating a login System [PHP] - by: GamingW[PHP][Coding][READ JEFF'S POSTS]

Started by: GamingWarrior | Replies: 24 | Views: 4,903

GamingWarrior
Banned

Posts: 70
Joined: Oct 2007
Rep: 10

View Profile
Dec 28, 2007 4:18 AM #74465
[SIZE="3"]Gaming Warrior's Login Tutorial V1[/SIZE]

I have been coding for 2 years now, so this tutorial probably needs someone with a basic knowlegde of PHP, and some function.

Things we will need
- Mysql Access
- Server or get one free www.wamp.com
- Some basic PHP knowledge.
- PHP 4 or later installed
- Login.php

Functions We will Use
- http://www.w3schools.com/php/php_mysql_insert.asp
- http://ca3.php.net/mysql_query
- http://ca3.php.net/manual/en/function.md5.php
- http://ca3.php.net/session_start
- http://ca3.php.net/manual/en/function.trim.php
- http://ca3.php.net/manual/en/ref.session.php
- http://ca3.php.net/manual/en/function.empty.php
- http://ca3.php.net/manual/en/function.mysql-connect.php

Step1.
To create our login system we will need 1 mysql table called "users". So lets begin...


// The mysql_query() function runs a MYSQL script

mysql_query("CREATE TABLE users(

'id' INT(11) UNSIGNED AUTO_INCREMENT,
'username' VARCHAr(225) NOT NULL,
'password' VARCHAr(225) NOT NULL,

UNIQUE KEY(id)")or die(mysql_error());


?>

// What we just did basically was create a table in our DATABASE (holds data), and we gave it the columns for a login system. You can add alot more to it, but this is short and simple.



Step2.
Now we need a test user for the login system, so we run another QUERY, this Statement is called INSERT. (Look at the functions list i showed you)



// Username: Demo Password: 12345

$query = mysql_query("INSERT INTO users (username,password) VALUES ('Demo','12345')") or die("LOL, didnt work");

// You can edit the information to your own likes.

?>



Step3.
The next step is our LOGIN.PHP page I told you to create earlier in this Tutorial. If you did this then insert the following code in it...















Username:
Password:
 



Step 4.
The final step is to validate the login once the user attempts to login.

THIS CODE GOES ON TOP OF THE FORM!!!


// Hello, this is Gaming Warrior walking you through the rest of the tutorial
session_start(); // we are going to use sessions, not cookies this time.
// Connect to the data
$dbhost = ''; // Localhost default
$dhname = '';
$dbuser = '';
$dbname = '';
mysql_connect($dbhost,$dbuser,$dbpass) or die("Website is Offline");
mysql_select_db($dbname);
// Now we need to set the variables

$form = $_POST['Submit'];
$username = trim($_POST['username']);
$password = trim($_POST['password']);

if($_SESSION['is_online']==false){ // Check if the user is online, I will explain this later
if(isset($form)){ // Checks if the user has submitted the form
if(empty($username)) || (empty($password)){ // if the user has filled in the fields

echo 'Please fill in all the fields';

}
else{

$username = mysql_real_escape_string($username); // Prevent SQL injections
$password = mysql_real_escape_string(md5($password)); // Prevent SQL injections, and HASH the password
$check = mysql_query("SELECT * FROM users WHERE username = '$username' && password ='$password'")or die(mysql_error()); //this function selects the data from the mysql, with the username and password given

if(mysql_num_rows($check)==0){ // Check how many rows has that username and password (if 0 die) (if 1 success) //

echo 'Wrong Username/Password';
}
else{

$_SESSION['is_online'] = true; // This is a session, you can read about it on the links I gave you, this session will be a data that will be on every page.
$_SESSION['username'] = stripslashes($username); // This is the username we put in the session, to retrieve the online user's information

die("SUCCESS, you are now logged in ".$_SESSION['username']);

}
}
}
else{

die("You are already logged in"); // Put custom message for users that are already logged in

}
}
?>


To show the username just do


session_start(); // You need this on every page to get the user session
echo 'Hello '.$_SESSION['username'] . ' You are logged in';

?>




Well everyone that was it, I don't expect you to understand without reading those links, and going through the basics, but this is a little preview on how its done. This was done very quickly, and its for learning purpose, not for the WWW. Becareful, and read about security, and how to protect yourself against harmful scripts.

I will also post Registration, and V2 of this. Maybe it will be a video tutorial you never know.

thankyou :p
Raffi
2

Posts: 4,326
Joined: Aug 2006
Rep: 10

View Profile
Dec 28, 2007 7:50 AM #74503
Wow, this looks helpful.
GamingWarrior
Banned

Posts: 70
Joined: Oct 2007
Rep: 10

View Profile
Dec 28, 2007 10:07 AM #74511
Quote from Raffi
Wow, this looks helpful.



Hey Raff, try it out, its really amazing once it works. I promise you it will make you want to learn more. Just use my tutorial, and add some more to it....
Chimaera
2

Posts: 2,490
Joined: Oct 2005
Rep: 10

View Profile
Dec 28, 2007 2:32 PM #74525
Yay, feed the script-kiddy generation.
Satyr
2

Posts: 62
Joined: Nov 2007
Rep: 10

View Profile
Dec 28, 2007 4:01 PM #74532
I'm to lazy to read and download all that. I used to use HTML coding, but I only needed the program notepad for that. Looks like it could help though!
GamingWarrior
Banned

Posts: 70
Joined: Oct 2007
Rep: 10

View Profile
Dec 28, 2007 11:13 PM #74599
Quote from Satyr
I'm to lazy to read and download all that. I used to use HTML coding, but I only needed the program notepad for that. Looks like it could help though!


I sort of find notepad useless when it comes to HTML, its a waste of time. Getting something like Dreamweaver gets the job done really easily. But when you coding something really complicated, it comes down to writing the code yourself for an HTML layout. I make my layouts using Template Classes and dreamweaver.

Note: This tutorial is really quick to read, it may look long but its not lol :p. You just have to copy paste, but if you don't use it, keep this as a reference when you want to code a login system.

Good luck to you all.
Jeff
Administrator
1

Posts: 4,356
Joined: Dec 2007
Rep: 10

View Profile
Dec 29, 2007 2:07 AM #74631
Horribly written, littered with errors and security flaws. People read tutorials to learn how to make things, not to get confused and possibly hacked. If you're going to write a tutorial, be sure there are no spelling mistakes (especially in your code for goodness sake), there are no security flaws (don't pass it off as telling people to learn security, it's your responsibility as the tutorial writer to help people), and most of all, make sure it works.

Your first error is in your first code, the sql query. While executing this in both a php file and in phpMyAdmin, it didn't work and would error, so I made my own code:

$sql = 'CREATE TABLE `users` ('
. ' `user_id` INT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY, '
. ' `username` VARCHAR(255) NOT NULL, '
. ' `password` VARCHAR(255) NOT NULL'
. ' )'
. ' ENGINE = innodb;';
$result = mysql_query($sql) or die(mysql_error());


That is the proper code for it (in php), and I have tested and re-tested this on both a live and wamp environment, which is what you should do instead of producing shoddy tutorials.

Second and the one that proves the most that you didn't actually take time in this tutorial is when you're creating the user 'Demo'.

If it's not obvious what you did wrong you should be ashamed. When you make the user, you've forgotten that the password is encoded in an MD5 hash! So anyone using this tutorial will be SOL in testing it because they can't log in, because you've forgotten to hash the password field when creating the user!

So here's a fix...

$sql = 'INSERT INTO `users` (`user_id`, `username`, `password`) VALUES (NULL, \'Demo\', \'' . md5("12345") . '\');';
$result = mysql_query($sql) or die(mysql_error());


Third error (you must have done a lot of copying and pasting), lays within the HTML you pasted. The ID and Name values for the password field say that they are the username field. So essentially you have two username fields and no password field.

Another fix...















Username:
Password:
 



Christ.

Now let's move on to your main code. First errors I notice are security errors,

$form = $_POST['Submit']; 
$username = trim($_POST['username']);
$password = trim($_POST['password']);


Should be

$username = clean(trim($_POST['username']));
$password = clean(trim($_POST['password']));


clean(); is a custom function that looks like this:

function clean($text) {
return strip_tags(htmlspecialchars(addslashes(stripslashes($text)), ENT_QUOTES));
}


This has already been created in my document. This is a necessary security function and I urge you to adopt it.

You must clean all input, no exceptions. Also the $form variable can also cause a form spoof to allow a user to log in as an administrator, and has been removed and fixed later on in the code.

Next part of the code:

	if(isset($form)){


Seeing as how I removed the $form variable, we change it to this to make SURE that someone has submitted data, and that data is post:

	if($_SERVER['REQUEST_METHOD'] == 'POST'){


Moving on...

         if(empty($username)) || (empty($password)) {   


Mal-formed.

         if(empty($username) || empty($password)) {   


Fixed. Next...

	$username = mysql_real_escape_string($username); // Prevent SQL injections 
$password = mysql_real_escape_string(md5($password)); // Prevent SQL injections, and HASH the password


This doesn't prevent SQL injections to the fullest it could, you don't encode special characters or anything. So, in addition to me clean() function, I have a mysql_clean() function which essentially is the clean() function except with addslashes() replaced with mysql_real_escape_string().

That looks like...

function mysql_clean($text) {
return strip_tags(htmlspecialchars(mysql_real_escape_string(stripslashes($text)), ENT_QUOTES));
}


and we make the changes...

	$username = mysql_clean($username); // Prevent SQL injections 
$password = mysql_clean(md5($password)); // Prevent SQL injections, and HASH the password


Next is a simple error:

$_SESSION['is_online'] == true; // This is a session, you can read about it on the links I gave you, this session will be a data that will be on every page. 


You have two = signs. This is not an if statement, it's a definition, you need only one.

$_SESSION['is_online'] = true; // This is a session, you can read about it on the links I gave you, this session will be a data that will be on every page. 


Below that you have a huge mistake:

$_SESSION['username'] = stripslashes($username); // This is the username we put in the session, to retrieve the online user's information 


Never ever take out the slashes when storing a variable! Only do this when displaying the name!

$_SESSION['username'] = $username; // This is the username we put in the session, to retrieve the online user's information 


Next change

die("SUCCESS, you are now logged in ".$_SESSION['username']); 


to

die("SUCCESS, you are now logged in ".stripslashes($_SESSION['username'])); 


And lastly, you're missing a trailing } before


}
else{

die("You are already logged in"); // Put custom message for users that are already logged in

}


So simply change the above to

}
}
else{

die("You are already logged in"); // Put custom message for users that are already logged in

}


Honestly. How you could have possibly produced this is beyond me. People generally check their code before they write a tutorial on it.
GamingWarrior
Banned

Posts: 70
Joined: Oct 2007
Rep: 10

View Profile
Dec 29, 2007 2:11 AM #74633
What the **** was the difference from ISSET and $_REQUEST?

mysql_real_escape_string is the proper way of cleaning SQL injections, it had no problem in there.

ADDING TICKS IS FOR RESERVED WORDS IN SQL


I made a mistake adding 2 '==' was a simple typing mistake.

}
}
else{

die("You are already logged in"); // Put custom message for users that are already logged in

}


Again I forgot a bracket, I wrote the tutorial in the post, its not something old i posted here. Common coding error.


MYSQL_CLEAN IS PHP3.0, HOW OLD ARE YOU? REMOVING SLASHES BEFORE OR AFTER MAKES NO DIFFERENCE



// The mysql_query() function runs a MYSQL script 

mysql_query("CREATE TABLE users(

'id' INT(11) UNSIGNED AUTO_INCREMENT,
'username' VARCHAr(225) NOT NULL,
'password' VARCHAr(225) NOT NULL,

UNIQUE KEY(id)")or die(mysql_error());


?>


with or without the TICKS ``, none of the words a reserved in the SQL!


ITS PERFECTLY FINE. I made it in Dreamweaver then paste it here

Its the text NaME that counts not the ****ing ID. Id is for Js solutions















Username:
Password:
 




Overall you found 2 common mistakes, missing }, and i added an extra '=' somwhere. Thankyou
Jeff
Administrator
1

Posts: 4,356
Joined: Dec 2007
Rep: 10

View Profile
Dec 29, 2007 2:18 AM #74637
Quote from GamingWarrior
What the **** was the difference from ISSET and $_REQUEST?


Look at the full code, you'll understand.

Quote from GamingWarrior

mysql_real_escape_string is the proper way of cleaning SQL injections, it had no problem in there.


Yes, but you also didn't protect against PHP, HTML, JS, etc. injections, in which a user can set their username as coding.

Quote from GamingWarrior
ADDING TICKS IS FOR RESERVED WORDS IN SQL


Pardon?

Quote from GamingWarrior

I made a mistake adding 2 '==' was a simple typing mistake.

}
}
else{

die("You are already logged in"); // Put custom message for users that are already logged in

}


Again I forgot a bracket, I wrote the tutorial in the post, its not something old i posted here. Common coding error.


That's my point. You still made them, and you obviously didn't check your own coding.

Quote from GamingWarrior
MYSQL_CLEAN IS PHP3.0, HOW OLD ARE YOU? REMOVING SLASHES BEFORE OR AFTER MAKES NO DIFFERENCE


Are you retarded?

Mysql_Clean as I even said and provided the code for is a function I made up.
Dudeman
2

Posts: 2,206
Joined: Aug 2005
Rep: 10

View Profile
Dec 29, 2007 2:21 AM #74640
Quote from JeffSL
[SIZE="1"]Look at the full code, you'll understand.



Yes, but you also didn't protect against PHP, HTML, JS, etc. injections, in which a user can set their username as coding.



Pardon?



That's my point. You still made them, and you obviously didn't check your own coding.



Are you retarded?

Mysql_Clean as I even said and provided the code for is a function I made up.[/SIZE]

Thank you for the much needed ownage.

Metal dog, take this guys advice. It's obvious that he knows his shit.

I was pretty sure this was a copy-pasta tutorial until he pointed out all the spelling errors. Then I just laughed.
GamingWarrior
Banned

Posts: 70
Joined: Oct 2007
Rep: 10

View Profile
Dec 29, 2007 2:23 AM #74641
Quote from JeffSL
Look at the full code, you'll understand.



Yes, but you also didn't protect against PHP, HTML, JS, etc. injections, in which a user can set their username as coding.



Pardon?



That's my point. You still made them, and you obviously didn't check your own coding.



Are you retarded?

Mysql_Clean as I even said and provided the code for is a function I made up.



Yes, but you also didn't protect against PHP, HTML, JS, etc. injections, in which a user can set their username as coding.


thats why we use strip_tags, and htmlentities, I will post v2 and you'll know what i mean. Also isset function only checks if the user has submitted the form, I didn't want to check if the form was submitted from my server. I will include that in v2, thank you for your fixes.

Quote from Dudeman.
Thank you for the much needed ownage.

Metal dog, take this guys advice. It's obvious that he knows his shit.

I was pretty sure this was a copy-pasta tutorial until he pointed out all the spelling errors. Then I just laughed.


It wasnt copy pasted, I wrote it myself. He was talking about the HTML part. You don't have to tell me this guy knows his stuff, and just because of my previous acts around here, doesn't mean i took the time to learn PHP.
Jeff
Administrator
1

Posts: 4,356
Joined: Dec 2007
Rep: 10

View Profile
Dec 29, 2007 2:26 AM #74643
Quote from GamingWarrior
thats why we use strip_tags, and htmlentities, I will post v2 and you'll know what i mean. Also isset function only checks if the user has submitted the form, I didn't want to check if the form was submitted from my server. I will include that in v2, thank you for your fixes.


Except you never used strip_tags and htmlentities. I had to add them in. :|

Also the isset function checks if there is a $_POST variable with the name 'Submit'. My method checks if the page is being called with 'POST' enabled, which is far more efficient.
GamingWarrior
Banned

Posts: 70
Joined: Oct 2007
Rep: 10

View Profile
Dec 29, 2007 2:27 AM #74644
Quote from JeffSL
Except you never used strip_tags and htmlentities. I had to add them in. :|

Also the isset function checks if there is a $_POST variable with the name 'Submit'. My method checks if the page is being called with 'POST' enabled, which is far more efficient.


Thankyou. Although I am only beginning to learn, been 5 months. I learned most of it from reading Sam's Teach Yourself PHP.

I will use strip_tags, htmlentities, or maybe preg_match for special chars in my next tut.

@moderator dude:

He ment something like


function clean ($var1){

$var = msqyl_real_escape_string(strip_tags($var1));

//..etc


return $var;
}
Chimaera
2

Posts: 2,490
Joined: Oct 2005
Rep: 10

View Profile
Dec 29, 2007 10:21 AM #74708
Quote from JeffSL
Horribly written, littered with errors and security flaws... - ....People generally check their code before they write a tutorial on it.


My God, that was almost as ownage as Big Bangs Mega Flame..
LN3uq
2

Posts: 2,457
Joined: Dec 2004
Rep: 35

View Profile
Dec 29, 2007 7:40 PM #74785
Jaff?

GamingWarrior, I'd like an explanation of this pm. Really, I'm confused.
Quote from GamingWarrior
Been coding for 5 months now, i didn't steal the code. JeffSL pointed out 2 mistakes, most commonly known as typos

http://www.stickpageportal.com/forum...08#post1123408

refer to my post please.

Thankyou.

Er.
Why did you send me this?
What part do I play in this grand scheme?

Well, I guess Jeff's code could be used as a tutorial. If you want, you could post it in a new thread and I could get rid of this one maybe.
Website Version: 1.0.4
© 2025 Max Games. All rights reserved.