Page 1 of 1

CodeIgniter Text Based Mafia Game || Login/Usersonline part 3 Rate Topic: -----

#1 Denis1  Icon User is offline

  • D.I.C Head
  • member icon

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

Posted 20 April 2012 - 03:20 PM

Hello, Welcome to part 3 of the "CodeIgniter Text Based Mafia Game" tutorials. In this tutorials we are going to make a login to the members area and then make navigation so users are able to browse in the game. These tutorial will have the basic stuff like my old set of tutorials but we are going to take a different approach once we have created a basic forum in the next tutorial. After that I will then be creating advance tutorials which will include some advance techniques and new features. Also keep in mind that I will not be going over CSS because there is nothing different about how to use it in codeigniter, all you need to do is link it in the <head></head>(just as you would on anywhere else) on the index_top.php in the views/includes.

Sweet, Lets get started....

Login
I am sure you know how login works. We are going to retrieve their info from the database and match it up with information they typed in. The login is going to be quick because its just creating forms and validating.

Part 1 //Creating login_view.php and login function
Create a file in the views folder called login_views.php.
In that file create the login fields just like we did in the register. like so:
<div id="login_main">
	<h1 id="login_header">Login To Account</h1>
	<?php
	//See if the login_message variable exist and if so create one and display the
	// message from controller
	if (isset($login_message))
		echo $login_message;
	echo br();
	//Go to Home::validate and validate the user details
	echo form_open("home/validate");

	echo form_label("Enter your username", "Username");
	echo br();
	//simple form_input unlike the one used on the register page, because we don't
	//need to return informationto the user
	echo form_input("username", "");
	echo br(2);
	echo form_label("Enter your password", "Password");
	echo br();
	echo form_password("password", "");
	echo br(2);
	echo form_submit("submit", "submit");
	echo form_close();
	?>
</div>


now we need to be able to view this, so head over to the home controller and add a new function called login.
This function is used to just display out forms. We are going to use another function to validate our user input. The Add this function.

	function login() {
		//The login_view.php file created in the views folder
		$data['main_content'] = 'login_view';
		$this -> load -> view('template_view', $data);
	}


if all above is done correctly, your login page should be something like this.
Posted Image

Part 2 // Validating the user input,sessions and user model
Now we want to login to the user area. We are going to create another function called validate so we can run it and decide if the user details are correct and then direct them where need.

sessions
For me, I believe that codeigniter makes the business of sessions so easy with the library. Remember in the second tutorial we added sessions to be one of the libraries to be loaded, well now we are going to use it. If you read the session page on the user guide, you will see many ways of using this class. This is how we are going to use it.
This is one of the example.
$newdata = array(
                   'username'  => 'johndoe',
                   'email'     => 'johndoe@some-site.com',
                   'logged_in' => TRUE
               );

$this->session->set_userdata($newdata);


we are going to have an array and in this array we are going to place values to validate the user when the are logged in. The way we are going to use it is similar to the example above.... lets take a look

$data = array('username' => $this -> input -> post('username'), 'is_logged_in' => true, );
$this -> session -> set_userdata($data);


You can see by now I like to use the data variable when there is data involve. In our array we have username which take the username typed by the user, and then a variable called is_logged_in making it true, so we know that the username is logged in. This session is only going to be set when the user has passed all the validation.

Ok back to the validate function. This is how the function should be making use of the session class and also it is using the user_model class to connect to the database and see if data is correct.
function validate() {
		// Make sure that the fields are not empty using the build in form validation
		$this -> form_validation -> set_rules('username', 'Username', 'trim|required');
		$this -> form_validation -> set_rules('password', 'Password', 'trim|required');
		if ($this -> form_validation -> run() == FALSE) {
			$data['main_content'] = 'login_view';
			$data['login_message'] = "Please fill the empty field(s)";
			$this -> load -> view('template_view', $data);
		} else {
			// go to the user_model and run a function called validate so we can check the
			// data
			$query = $this -> users_model -> validate();
			if ($query)// if the user's information validate...
			{
				$data = array('username' => $this -> input -> post('username'), 'is_logged_in' => true, );
				$this -> session -> set_userdata($data);
				redirect("game");
			} else// incorrect username or password
			{
				$data['login_message'] = "Your username/password is invalid";
				$data['main_content'] = 'login_view';
				$this -> load -> view('template_view', $data);
			}
		}
	}


We are not done yet. If you try to run this you can see that the user_model doesn't have a function called validate, So we need to create one. Just like the function we created called create_member in the user_model.php file located in the models we are going to create validate.
	function validate() {
		// hash the user input password so we can compare it.
		$salt = "**********";
		$password = $this -> input -> post('password');
		$final_password = hash("sha512", "{$salt}.{$password}");
		// use codeigniter built in database class to help us query the database and
		// search for a match for the information inputed by the user
		$this -> db -> where('username', $this -> input -> post('username'));
		$this -> db -> where('password', $final_password);
		$query = $this -> db -> get('users');
		// if there is a match then return true to the validate function
		if ($query -> num_rows == 1) {
			return TRUE;
		}

	}

Notice just like in the register function I had way to salt and hash my password I will need to repeat the process so we can check when the pass the the user input is hash it matches the on in the database.
$salt = "**********";
$password = $this -> input -> post('password');
$final_password = hash("sha512", "{$salt}.{$password}");


Again your salt doesn't have to be ********* make it something hard to guess or it can even be another hash.

Part 3 // create the game controller.
This is the final part of login. When you run the game it will return we a error saying saying it can find the "game" controller can not be found. Well that's because we haven't created it yet.
Head over to the controller folder and create a file called game.php
This file is going to be used to control a lot of the key features in the game. This is the main inside game function.
<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');
//Note the name of the class is now game
class Game extends CI_Controller {

//The standard index function for the controller
	public function index() {
		$data['main_content'] = 'game_view';
		$this -> load -> view('template_view', $data);
	}

}

We now need to create game_view in the views folder.
Add something like this(just to test the success of login).
<div id="main_game">
  <h1 id="game_header">Welcome Inside</h1>
</div>



Now if everything is linked and all the files connected when you run the login page and login you should get this
Posted Image

Usersonline
Ok now it is time to enter and create the "inside" of our game and completely block the outside.
First we have to block users who are not signed in from entering the game through a url link like "/game".
To do this we are going to check for the cookie created in above in the index_top.php and index_bottom then place a way to check if the user is logged at the top of the index_top.php(on top of all html) like to

<?php
//Create a variable and store the user session 'is_logged_in'
$is_logged_in = $this -> session -> userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true) { // not logged in
redirect("login");
}
?>

When you view it the page will go in a redirect loop. To solve this I created a controller for both login and register pages. I then moved the function for login and register from the home controller to their respective controller. So both login and register are their independent pages, which are not linked to index_top.php.
	
// how to link single pages in the loader.
$this -> load -> view('login_view');


Make sure that all links and loaders are changed and make sure you have the full template on login_view so login_view should loop like this.
<!DOCTYPE html>
<head>
	<title>Login</title>
	<link rel="stylesheet" href="http://mafiamania.co.uk/css/style.css" type="text/css" media="screen" />
</head>
<body>
	<div id="wrap">
		<div id="login_main">
			<h1 id="login_header">Login To Account</h1>
			<?php
			$this -> session -> sess_destroy();
			//See if the login_message variable exsit and if so create one and disaple the
			// message from controller
			if (isset($login_message))
				echo $login_message;
			echo br();
			//Go to Home::validate and validate the userdetails
			echo form_open("login/validate");

			echo form_label("Enter your username", "Username");
			echo br();
			//simple form_input unlike the one used on the register page, because we dont
			//need to return informationto the user
			echo form_input("username", "");
			echo br(2);
			echo form_label("Enter your password", "Password");
			echo br();
			echo form_password("password", "");
			echo br(2);
			echo form_submit("submit", "submit");
			echo form_close();
			?>
		</div>
	</div>
</body>
</html>

and the controller should be link this.
<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');
// Changed the name of this calss to be my main class when you first go on my
// site.
class Login extends CI_Controller {

	public function index() {
		$this -> load -> view('login_view');
	}

	function validate() {
		// Make sure that the fields are not empty using the build in form validation
		$this -> form_validation -> set_rules('username', 'Username', 'trim|required');
		$this -> form_validation -> set_rules('password', 'Password', 'trim|required');
		if ($this -> form_validation -> run() == FALSE) {
			$data['login_message'] = "Please fill the empty field(s)";
			$this -> load -> view('login_view');
		} else {
			// go to the user_model and run a function called validate so we can cheak the
			// data
			$query = $this -> users_model -> validate();
			if ($query)// if the user's information validate...
			{
				$data = array('username' => $this -> input -> post('username'), 'is_logged_in' => true, );
				$this -> session -> set_userdata($data);
				redirect("game");
			} else// incorrect username or password
			{
				$data['login_message'] = "Your username/password is invalid";
				$this -> load -> view('login_view');
			}
		}
	}

}


Do the same for register_view and register controller.
Once you have completed both controllers check to make sure that the work and still creating accounts and logging.

Now its time to create users online page.
Head to the views and create a page called online_view.php. The controller for this will be the game controller.
This is my design for that page.

<div id="online_main">
  <h2>Users online</h2>
  <div id="online_main_list">
    <?php
$now = Now() - 300;
$sql = "SELECT username FROM users WHERE lastactive >= {$now} ORDER BY id ASC"; //  Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
 $online_name = htmlspecialchars($row->username);


  echo "{$online_name}"; // displays the names that fit our search
 
 if($i != $count) { // this counts the amount of people that are online and display the results.
  echo "<label> - </label>";
 }
 $i++;
}
echo "<p><center>Total Online: ".$count."</center></p>";
?>
  </div>
</div>


You can notice that the code sipplet i used here is from part 4 of my old set of tutorials Click here to have a read
In the models folder open users_model, we are going to create a function update the user's online status.
It is a very simple function to update the database
	function update_online($username) {
		$now = Now();
		$data = array('lastactive' => $now);

		$this -> db -> where('username', $username);
		$this -> db -> update('users', $data);

	}



Now open index_top.php so we can place the code to access the user_model to update the database. Before any html on the index_top.php page this is what you php code should look like
<?php
$is_logged_in = $this -> session -> userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true) {// not logged in
	redirect("login");
} else {
$username = $this -> session -> userdata('username');
$this -> users_model -> update_online($username);
}
?>


All you need to do now is create a controller. In the game controller create a simple online controller to view your online


Then link the online page on index_top.php
<a href="http://mafiamania.co.uk/game/online">Online</a>


If you run that you will see the database update with a Unix time, and you should see your name on the users online list

That's pretty much it for now. How you layout your pages and your online list is up to you. See you in next tutorial Where we will be making a forum

-Denis

Is This A Good Question/Topic? 0
  • +

Replies To: CodeIgniter Text Based Mafia Game || Login/Usersonline part 3

#2 Groudon  Icon User is offline

  • New D.I.C Head

Reputation: -18
  • View blog
  • Posts: 33
  • Joined: 01-December 12

Posted 02 December 2012 - 04:47 AM

This session username script for protect your web pages from guest users.
<?php session_start();include_once"config.php";
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
	header("Location: login.php");
}
?>

Was This Post Helpful? -2
  • +
  • -

#3 exray  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 08-December 12

Posted 08 December 2012 - 06:32 PM

Hi, ehm could you explain a little more where i put this ?

Quote

Part 2 // Validating the user input,sessions and user model
Now we want to login to the user area. We are going to create another function called validate so we can run it and decide if the user details are correct and then direct them where need.

sessions
For me, I believe that codeigniter makes the business of sessions so easy with the library. Remember in the second tutorial we added sessions to be one of the libraries to be loaded, well now we are going to use it. If you read the session page on the user guide, you will see many ways of using this class. This is how we are going to use it.
This is one of the example.
$newdata = array(
                   'username'  => 'johndoe',
                   'email'     => 'johndoe@some-site.com',
                   'logged_in' => TRUE
               );

$this->session->set_userdata($newdata);


we are going to have an array and in this array we are going to place values to validate the user when the are logged in. The way we are going to use it is similar to the example above.... lets take a look

$data = array('username' => $this -> input -> post('username'), 'is_logged_in' => true, );
$this -> session -> set_userdata($data);


You can see by now I like to use the data variable when there is data involve. In our array we have username which take the username typed by the user, and then a variable called is_logged_in making it true, so we know that the username is logged in. This session is only going to be set when the user has passed all the validation.

Ok back to the validate function. This is how the function should be making use of the session class and also it is using the user_model class to connect to the database and see if data is correct.
function validate() {
		// Make sure that the fields are not empty using the build in form validation
		$this -> form_validation -> set_rules('username', 'Username', 'trim|required');
		$this -> form_validation -> set_rules('password', 'Password', 'trim|required');
		if ($this -> form_validation -> run() == FALSE) {
			$data['main_content'] = 'login_view';
			$data['login_message'] = "Please fill the empty field(s)";
			$this -> load -> view('template_view', $data);
		} else {
			// go to the user_model and run a function called validate so we can check the
			// data
			$query = $this -> users_model -> validate();
			if ($query)// if the user's information validate...
			{
				$data = array('username' => $this -> input -> post('username'), 'is_logged_in' => true, );
				$this -> session -> set_userdata($data);
				redirect("game");
			} else// incorrect username or password
			{
				$data['login_message'] = "Your username/password is invalid";
				$data['main_content'] = 'login_view';
				$this -> load -> view('template_view', $data);
			}
		}
	}


We are not done yet. If you try to run this you can see that the user_model doesn't have a function called validate, So we need to create one. Just like the function we created called create_member in the user_model.php file located in the models we are going to create validate.
	function validate() {
		// hash the user input password so we can compare it.
		$salt = "**********";
		$password = $this -> input -> post('password');
		$final_password = hash("sha512", "{$salt}.{$password}");
		// use codeigniter built in database class to help us query the database and
		// search for a match for the information inputed by the user
		$this -> db -> where('username', $this -> input -> post('username'));
		$this -> db -> where('password', $final_password);
		$query = $this -> db -> get('users');
		// if there is a match then return true to the validate function
		if ($query -> num_rows == 1) {
			return TRUE;
		}

	}

Notice just like in the register function I had way to salt and hash my password I will need to repeat the process so we can check when the pass the the user input is hash it matches the on in the database.
$salt = "**********";
$password = $this -> input -> post('password');
$final_password = hash("sha512", "{$salt}.{$password}");


Again your salt doesn't have to be ********* make it something hard to guess or it can even be another hash.

Was This Post Helpful? 0
  • +
  • -

#4 New-Reign  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 22-April 13

Posted 10 June 2014 - 12:13 AM

Are there any plans to continue this tutorial, as far as I can see, it only goes up to part 3...

Thanks in advance.
Was This Post Helpful? 0
  • +
  • -

#5 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9579
  • View blog
  • Posts: 36,298
  • Joined: 12-June 08

Posted 10 June 2014 - 06:45 AM

It goes to part 10.

http://www.dreaminco...osmember=256139
Was This Post Helpful? 0
  • +
  • -

#6 New-Reign  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 22-April 13

Posted 10 June 2014 - 08:04 AM

View Postmodi123_1, on 10 June 2014 - 06:45 AM, said:



They aren't the code igniter versions. Thanks thought. I need the CI ones.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1