• (2 Pages)
  • +
  • 1
  • 2

Text Based Mafia Game || Login, Layout/design Part 3 Making a login page and having a an inside game design. Rate Topic: ***** 1 Votes

#1 Denis1  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 32
  • View blog
  • Posts: 101
  • Joined: 29-July 09

Posted 10 August 2010 - 04:06 PM

Before attempting this tutorial please make sure PART 2 is done Click here

Ok we are just going to dive right in with the login/index page. The login page is a way for users that have signed up to login in to their account and play the game. We are going to use sessions to save the user's id in the browser and while the are in the game it will bring up information based upon their id which is saved in the session. We will be preserving their information using sessions while they are login.

Index.php
The code that we are going to use for this login isn't very secure for now. In later parts we will talk about security issues such as sql injection.

Step One
- Creating the forms for index page.
Like i mentioned before we are not going to concentrate on the design of the pages and this is one of the pages that needs a very good design, You can do that after all everything else is done.

Create a page called Index.php, this is going to contain our login form that we will be using to login users.

add this code to connect to the database like we did in part 2. Make sure it is added before any html on the page.

<? include_once("connect.php"); ?>


We now need some html designs. The standard login have 2 fields (Username and password) with a submit button.

Add this html code in the body part of the page. Feel free to edit it as you see fit.

<form id="form1" name="form1" method="post" action=""><center>
  GAME LOGIN
  <br />
  <br />
  Username:
  <input type="text" name="Username" id="Username" />
  <br />
  <br />
Password:
<input type="password" name="password" id="password" />
  <br />
  <br />
  <input type="submit" name="Login" id="Login" value="Login" />
  </center>
</form>


that's just the html design codes.

Step Two - Checking database for the right account

Add this code on top of the html you have just added in the body section of the html.
<?
if(isset($_POST['Login'])) {
	$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.

if(empty($row['id'])){
	// check if the id exist and it isn't blank.
    echo "Account doesn't exist.";
	}else{
		
		if(md5($_POST['password']) != $row['password']){
			// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
            echo "Your password is incorrect."; 
			}else{
				echo "Account available";
			}
	}
}
?>



The php above has comment to explain what is going on at each stage. You can notice that when you get the login details right it will just echo "Account available". this is so for now because we are doing it in bits. So you can understand what is going on at each stage.

Step Three - Validations
In this step we are going to focus on the validations and the errors. such as if the type in nothing in the name field or the password field.

Replace the php you have already added with this.
<?
if(isset($_POST['Login'])) {
	
	if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
         echo "Invalid  Username.";
		 }else{
			 
			 $query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.

if(empty($row['id'])){
	// check if the id exist and it isn't blank.
    echo "Account doesn't exist.";
	}else{
		
		if(md5($_POST['password']) != $row['password']){
			// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
            echo "Your password is incorrect."; 
			}else{
				echo "Account available";
			}
			}
	}
}
?>


we added simple validation to check if the username is in the right format before any information is fetched from the database.

Step Four
- Inside Game.

We are going to try use the information and set a session and redirect the user to another page (Inside the game) using the php header.

Let me break down this step -
  • We are going to Create a sample page to redirect to.
  • Save the users id in a session
  • Log the users ip and if information is typed in correctly redirect to sample page.


First create a sample page. i am going to called mine Sample.php, all i am going to add on sample.php is WELCOME.

Back to index.php. now we want to log their ip (There are many reasons we need to log users ip we will talk about it more on the security section.) and save their user id in session.

Update the php code on the index.php with the one below
<?
if(isset($_POST['Login'])) {
	
	if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
         echo "Invalid  Username.";
		 }else{
			 
			 $query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.

if(empty($row['id'])){
	// check if the id exist and it isn't blank.
    echo "Account doesn't exist.";
	}else{
		
		if(md5($_POST['password']) != $row['password']){
			// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
            echo "Your password is incorrect."; 
			}else{
				
				if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already 
		$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
		}else{
		
		$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
		
		if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {	
		$row['login_ip'] = $row['login_ip'];
		}else{	
		$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
		}
		}
			}
			}
	}
}
?>


We have added a simple code to store the users ip using the "$_SERVER['REMOTE_ADDR']" Which gets the ip address from the user. If the sure login from another ip address the code will add it to an array with the other ip address (This is useful because we can see all the ip addresses that have gain access to the account in case it gets hacks etc)

For the header to redirect us to Sample you need to start a session on the connect.php
on connect.php add following code on LINE 1 (Make sure nothing is above it.
<? session_start();
ob_start();
?>


Back on index.php so far the code we have doesn't update the mysql with the information we are going to be using.

Replace the index.php php code with the one below.

<?
if(isset($_POST['Login'])) {
	
	if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
         echo "Invalid  Username.";
		 }else{
			 
			 $query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.

if(empty($row['id'])){
	// check if the id exist and it isn't blank.
    echo "Account doesn't exist.";
	}else{
		
		if(md5($_POST['password']) != $row['password']){
			// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
            echo "Your password is incorrect."; 
			}else{
				
				if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already 
		$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
		}else{
		
		$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
		
		if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {	
		$row['login_ip'] = $row['login_ip'];
		}else{	
		$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
		}
		}
		
	$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
 
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());

// to test that the session saves well we are using the sessions id update the database with the ip information we have received.

header("Location: Sample.php"); // this header redirects me to the Sample.php i made earlier
	
		
			}
			}
	}
}
?>


the code above saves our user id in a session and then if all the information is correct it will redirect us to Sample.php. If you check your browser cookies you can see the PHPSESSID saved and it content is your user id. if you check your database you can see your ip in the users ip and if you login from another ip you can see the ip added to the one on there already.

to recap in this step we saved the ip from the remote ADDR and also we saved their session in the browser.

Step Five - Destroying sessions.

We are going to learn to destroy sessions in case the want to log-out. this may not be the safest/ best way of doing things but it is simple enough to follow and understand.

add this php code on index.php.
<?
if(isset($_SESSION['user_id'])) {

// if already logged in.

session_unset();

session_destroy(); 

echo "You have been logged out.";
}
?>

The code destroy the session that we have set when we login.

On Sample page add A text like Click here to log out and link it to the index.php like this.
<a href="index.php">LogOut</a>

this is co it will take them to index and destroy their session.

Thats about it for this part. We have created a login page and used session to save the users id in the browser and then we user header to redirect the user to a sample page ( will be the inside game).

In the next tutorial we are going to focus more on the layout of the game and the structure of the game. also in the next step we are going to create a small forum for users to post on it. Things are going to start getting confusing but i will do my best to explain bit by bit.

If you have any questions/ suggestions or you see any grammatical error or any way of improving my code please post below and i will update it.
Thanks.


--------
Mod: the code can be found here:
https://github.com/m...ext_Based_Mafia

This post has been edited by modi123_1: 08 January 2014 - 09:03 PM


Is This A Good Question/Topic? 2
  • +

Replies To: Text Based Mafia Game || Login, Layout/design Part 3

#2 dragonfire1119  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 31-January 10

Posted 15 August 2010 - 12:10 AM

Ok you did miss spell on one thing "fouse" down at the bottom is focus. Great Tutorials :bananaman:

This post has been edited by dragonfire1119: 15 August 2010 - 12:10 AM

Was This Post Helpful? 0
  • +
  • -

#3 Denis1  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 32
  • View blog
  • Posts: 101
  • Joined: 29-July 09

Posted 15 August 2010 - 02:43 PM

View Postdragonfire1119, on 14 August 2010 - 11:10 PM, said:

Ok you did miss spell on one thing "fouse" down at the bottom is focus. Great Tutorials :bananaman:


thanks :), changes have been made

This post has been edited by Denis1: 15 August 2010 - 02:44 PM

Was This Post Helpful? 0
  • +
  • -

#4 Petsarve  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 45
  • Joined: 17-February 10

Posted 17 August 2010 - 11:29 AM

Really good tutorial!

Even if I'm not the least interested in making a text based maffia game, I'ts really useful to see how an actual application is built! It kind of ties the strings together when you have learned the mechanics of PHP/MySQL.
Keep it up!
Was This Post Helpful? 0
  • +
  • -

#5 jin0616  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-June 09

Posted 10 October 2010 - 03:43 AM

I have followed everything that you said.
It works fine.
but "You have been logged out" is not coming up.
i put the
<?php
if(isset($_SESSION['user_id'])) {

// if already logged in.

session_unset();

session_destroy(); 

echo "You have been logged out.";
}
?>


at the bottom of all the php codes but above the html code in index.php

why is that?
Was This Post Helpful? 0
  • +
  • -

#6 Guest_millsie*


Reputation:

Posted 14 October 2010 - 10:11 PM

View Postjin0616, on 10 October 2010 - 02:43 AM, said:

I have followed everything that you said.
It works fine.
but "You have been logged out" is not coming up.
i put the
<?php
if(isset($_SESSION['user_id'])) {

// if already logged in.

session_unset();

session_destroy(); 

echo "You have been logged out.";
}
?>


at the bottom of all the php codes but above the html code in index.php

why is that?



I had to change it to this as the connect.php was calling the session_start(). I also had to change the session_unset() to unset($_SESSION['user_id']);

works like a charm now :)

<?php
	include_once("connect.php");
	if(isset($_SESSION['user_id'])) {
		// if already logged in.
		unset($_SESSION['user_id']);	
		session_destroy();
		echo "You are logged out";
	}
?>



hope this helps :)
Was This Post Helpful? 0

#7 aaron1178  Icon User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 169
  • View blog
  • Posts: 1,297
  • Joined: 22-October 08

Posted 15 October 2010 - 10:18 PM

Actually, you should always use "session_unset", this is the propper way to do things.
Was This Post Helpful? 0
  • +
  • -

#8 millsons  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 07-October 11

Posted 18 October 2011 - 12:55 PM

when i make a new page i get logged out so i cant view the page how can i fix that?
Was This Post Helpful? 0
  • +
  • -

#9 Shadowing  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 34
  • Joined: 26-November 11

Posted 30 November 2011 - 09:26 AM

I keep getting a error on line 9

<? include_once("connect.php"); ?>

<html>
<body>

<?php
if(isset($_POST['Login'])) {
	
	if(ereg('[^A-Za-z0-9]', $_POST['name'])){ // before we fetch anything from the database we want to see if the user name is in the correct format.
         echo "Invalid  Username.";
		 }else{
			 
			 $query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.

if(empty($row['id'])){
	// check if the id exist and it isn't blank.
    echo "Account doesn't exist.";
	}else{
		
		if(md5($_POST['password']) != $row['password']){
			// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
            echo "Your password is incorrect."; 
			}else{
				
				if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already 
		$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
		}else{
		
		$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
		
		if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {	
		$row['login_ip'] = $row['login_ip'];
		}else{	
		$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
		}
		}
			}
			}
	}
}
?>

<form id="form1" name="form1" method="post" action=""><center>
  GAME LOGIN
  <br />
  <br />
  Username:
  <input type="text" name="Username" id="Username" />
  <br />
  <br />
Password:
<input type="password" name="password" id="password" />
  <br />
  <br />
  <input type="submit" name="Login" id="Login" value="Login" />
  </center>
</form>

</body>
</html>

Was This Post Helpful? 0
  • +
  • -

#10 Shadowing  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 34
  • Joined: 26-November 11

Posted 01 December 2011 - 11:14 AM

Ok I found out finally why i was getting the error on line 9

if(!preg_match('/^[A-Za-z0-9]{5,20}$/',$_POST['name'])){ // before we fetch anything from the database we want to see if the user name is in the correct format.
         echo "Invalid  Username.";
		 }else{



Its because the tutor has
]{5,20}$/',$_POST['name']

when it should be
]{5,20}$/',$_POST['username']


you only put name and not username.

After talking to alot of people at phpfreaks.com I they told me a more superior way of writing this code.

if(!preg_match('/^[A-Za-z0-9]{5,20}$/',$_POST['Username'])){


5,20 makes sure your username is at least 5 characters long and not anymore then 20 characters long.

Also I had to change ereg to !preg_match because PHP 5.3 doesnt support the command ereg anymore.

Also you have to add delimiters "/" before and after. delimiters makes it so the code keeps repeating it self so each character gets checked other wise usernames such as o"$%^&* would match because the o at the beginning would be matched and the engine would stop reading.

But since I added 5,20 there is another problem and thats when you have to ad ^ and $ where I added it.
This is because after 5 characters are read any bad characters will pass and becoem true. So this would pass obiwan"$%^&*.

Anyways now i can move on to step 4 lol :)
Was This Post Helpful? 0
  • +
  • -

#11 Shadowing  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 34
  • Joined: 26-November 11

Posted 05 December 2011 - 02:54 AM

Alright I couldnt continue to step 4 lol. There is a few more problems with step 3 that I will show how I fixed them.

The entire process of keeping people from accessing the sample page with out being loged in does not work. Plus the fact of logging in auto directs you right back to the index page.

First thing DO NOT add this code to the index file

<?
if(isset($_SESSION['user_id'])) {

// if already logged in.

session_unset();

session_destroy(); 

echo "You have been logged out.";
}
?>


This is why its sending you back to the index page. The session does work but this destorys the session after you create the id in the session so the script in the safe file reads no session existing and doesnt think you are loged in.

I went ahead and buffed this up by alot lol. I made it so it auto logs you out after 15 minutes of inactivty you can change the time limit your self.

First we need to add this code to your index file
$_SESSION['login_time'] = time(); // stores the log in time of the user

this will record the log in time of the user into the session

and then add this to your Safe file

if ($_SESSION['login_time'] < strtotime('-1 minutes')) {
 	// logs user out after 15 minutes and redirects to login and ends session
 		
 		header("Location: index.php");
 		exit();
 		session_destroy();
 		echo "You have been loged out.";
}





at this step of this game your safe file should look just like this


<?php include_once("connect.php");


if(isset($_SESSION['user_id'])) { // checks for id in session
 	
 	$sql = "UPDATE users SET lastactive = NOW() WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'";
 	 		
 	mysql_query($sql); // updates the last activity of user
		
 	           
 	if ($_SESSION['login_time'] < strtotime('-1 minutes')) {
 	// logs user out after 15 minutes and redirects to login and ends session
 		
 		header("Location: index.php");
 		exit();
 		session_destroy();
 		 		
}
}
?>



and your index should look like this

<? include_once("connect.php"); ?>

<html>
<body>

<?php

if(isset($_POST['Login'])) {
	if(!preg_match('/^[A-Za-z0-9]{5,20}$/',$_POST['Username'])) { // checks username format.         
	echo "Invalid  Username.";
	} else {
		$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'"; 
		$result = mysql_query($query) or die(mysql_error());
		$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
	
		if(empty($row['id'])){
			// check if the id exist and it isn't blank.
			echo "Account doesn't exist.";
		} else {
			if(md5($_POST['password']) != $row['password']){
				// if the account exist this is matching the password with the password typed in the password field.
				echo "Your password is incorrect."; 
			} else {
								
				if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already 
					$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
					}
					
					$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
					
					if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
						$row['login_ip'] = $row['login_ip'];
					} else {
						$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];	
					}
					
					$_SESSION['user_id'] = $row['id'];// stores the id of the user
					$_SESSION['login_time'] = time(); // stores the log in time of the user

					
					$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
					or die(mysql_error());
					
					// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
					
					header("Location: sample.php"); // redirects me to main.php
					
					
				
			     }	
		  }
	}	
}

?>					
<form id="form1" name="form1" method="post" action=""><center>
  GAME LOGIN
  <br />
  <br />
  Username:
  <input type="text" name="Username" id="Username" />
  <br />
  <br />
Password:
<input type="password" name="password" id="password" />
  <br />
  <br />
  <input type="submit" name="Login" id="Login" value="Login" />
  </center>
</form>

</body>
</html>	


and your sample page should look like this

	<?php require("Safe.php"); ?>


<html>
<body>


WELCOME



<a href="index.php">LogOut</a> 



<body>
<html>


I have the log out time set to 1 minute so I can test that it is working. Log in wait over a minute and then refresh your page and it will take you back to the login page since your session is expired and log in again and you will see that you can refresh the page as many times as you want under a minute.


On a ending note its because all these errors in this tutor is the reason I learned ALOT. Coping and pasting code is really not going to get you anywhere.

make sure you do the SQL, PHP, HTML, CSS and Javascript tutors at http://www.w3schools.com/
I will see you guys on step 4 in the future.
Was This Post Helpful? 0
  • +
  • -

#12 Shadowing  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 34
  • Joined: 26-November 11

Posted 05 December 2011 - 03:03 AM

I just wanted to add that

session_start();
ob_start();

should be at the top of your connect.php file

your connect.php file should look like this right now at this step

<?php session_start();
ob_start(); 

$mysql_server = "localhost"; // localhost is common on most hosts.

$mysql_user = "**********"; //  this is the name of your username of the server.

$mysql_password = "********"; // the password connected to the username. MAKE IT COMPLEX.

$mysql_database = "*********"; // the database name of where to connect to and where the information will be help.

$connection = mysql_connect("$mysql_server","$mysql_user","$mysql_password") or die("Unable to establish a DB connection");

$db = mysql_select_db("$mysql_database") or die("Unable to establish a DB connection");
?>

Was This Post Helpful? 0
  • +
  • -

#13 Shadowing  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 34
  • Joined: 26-November 11

Posted 05 December 2011 - 03:22 AM

I just realize that the Safe.php file doesnt get created till step 4. but I had to mention it here on step 3 anyways.

So if you are reading my changes in this step and are confused about the safe.php file im using. Then that is why I have a safe file cause its being created in step 4.

but like i said i couldnt make it all work with out using the safe file in step 3 so really the safe file should be in step 3.

Cheers!
Was This Post Helpful? 1
  • +
  • -

#14 Phantom Coder  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 13
  • Joined: 26-April 09

Posted 05 February 2012 - 11:50 PM

Thanks a lot for the third installment of your tutorial!!!!! awesome.

it seems i been getting a lot of functions lately. i thought i share them with you.

<?php
/**
 * @author Phantom Coder
 * @copyright 2010-2012
 */
 
function connect() {
	 // localhost is common on most hosts.
	 $mysql_server = "localhost";
	 //  this is the name of your username of the server.
	$mysql_user = "dbuser";
	 // the password connected to the username. MAKE IT COMPLEX.
	$mysql_password = "P@ssw0rd";
	 // the database name of where to connect to and where the information will be help.
	$mysql_database = "dbname";
	$connection = mysql_connect("$mysql_server","$mysql_user","$mysql_password") or die ("Unable to establish a DB connection");
	$db = mysql_select_db("$mysql_database") or die ("Unable to establish a DB connection");
 }

 // This function is going to help us filter out bad email from the good one and it makes sure the email enter is in the format of as@as.com
 function checkEmail($str) {
	return preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}

// this is a send email function that will help us send email to the registered users.
function send_mail($from,$to,$subject,$body) {
	$headers = '';
	$headers .= "From: $from\n";
	$headers .= "Reply-to: $from\n";
	$headers .= "Return-Path: $from\n";
	$headers .= "Message-ID: <" . md5(uniqid(time())) . "@" . $_SERVER['SERVER_NAME'] . ">\n";
	$headers .= "MIME-Version: 1.0\n";
	$headers .= "Date: " . date('r', time()) . "\n";

	mail($to,$subject,$body,$headers);
}

 // sanitizes the input from the users in our forms
function protect($string) {
    return mysql_real_escape_string(strip_tags(addslashes($string)));
}

//error output for status messages
function outputerror($string) {
	echo "<div id=\"outputerror\">" . $string . "</div>";
}

//normal output for status messages
function outputnormal($string) {
    echo "<div id=\"outputnormal\">" . $string . "</div>";
}

// keeps the copright date current
function copyrightdate() {
     $time = time ();
     $year= date("Y",$time);
     echo $year;
}

// Logs out the users.
function logout() {
	// if already logged in.
	if(isset($_SESSION['user_id'])) {
		unset($_SESSION['user_id']);
		session_destroy(); 
		outputnormal("You have been logged out.");
	}
}

?>



I hope you find them useful as I am. I'm going on to part 4 NOW!!!!!
Was This Post Helpful? 0
  • +
  • -

#15 sakred  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 1
  • Joined: 21-January 13

Posted 21 January 2013 - 10:58 PM

I can't seem to log in. It always says invalid password when it's correct according to the database. Also if i go back to the register.php page and make a new account it doesn't log the ip. Or nothing ever gets stored into the login_ip row of the database. I'm not sure what i'm doing wrong. Some help would be MUCH appreciated. Thanks. Oh and i'll put the code for my index page and maybe you will see something i don't. And another side note. My database is "Users" instead of "users". So that's why mine is capitalized.

<? include_once("connect.php"); ?>
<? require 'functions.php'; ?>
<html>
<head>
<title>Index</title>
</head>
<body>


<?
if(isset($_POST['Login'])) {

       if (ereg('/^[A-Za-z0-9]{5,20}$/', $_POST['Username'])) {// Before we fetch anything from the database we want to see if there name is in the correct format.
	                       echo "Invalid Username.";
						   }else{

         $query = "SELECT password,id,login_ip FROM Users WHERE 
		 name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the datatbase and get the password, id, and login ip that belongs to the name in the username field.

if(empty($row['id'])){
            // Check if the id exists and it isn't blank.
			 echo "Account doesn't exist.";
			 }else{
			 
			 if(md5($_POST['password']) != $row['password']){
			 // if the account does exist this is matching the password with the password typed in the field. Notice to read the md5 has we need to use the md5 function
			 echo "Your password is incorrect.";
			      }else{
				  
				  if(empty($row['login_ip'])){ // Checks to see if the login ip has an ip already
				  $row['login_ip'] = $_SERVER['REMOTE_ADDR'];
				  }else{
				  
				  $ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip on the database it will store it.
				                 if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
								 $row['loging_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
				          }
						 }
					$_SESSION['user_id'] = $row['id']; // This line of code is ver important. This saves the user id in the php session so we can use it in the game to display information to the user.
					$_SESSION['login_time'] = time(); // stores the login time of the user
					
					$result = mysql_query("UPDATE Users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
					
or die(mysql_error());

					
					// To test that the session saves well we are using the sesssions id update the database with the ip information we have received.
					
					header("Location: Sample.php"); // This header redirects me to the Sample.php i made earlier
					
				
					 }
				     }
			}		 
		}
?>




<form id="form1" name="form1" method="post" action=""><center>
GAME LOGIN
<br/>
<br/>
Username:
<input type="text" name="Username" id="Username"/>
<br/><br/>
Password:
<input type="password" name="password" id="password" />
<br/> <br/>
<input type="submit" name="Login" id="Login" value="Login" />
</center>
</form>

</body>
</html>


Was This Post Helpful? -1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2