Page 1 of 1

CodeIgniter Text Based Mafia Game || Register part 2 Rate Topic: -----

#1 Denis1  Icon User is offline

  • D.I.C Head
  • member icon

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

Posted 16 April 2012 - 01:12 PM

Hello, and Welcome to part 2 of CodeIgniter Text Based Mafia Game. In this tutorial we are going to be making register and maybe login so we can have an inside game and a outside game. Lets dive straight in... obviously make sure you have completed the first tutorial. Please bear with me I promise you great results. I am writing half of this tutorial with a hangover so there may be things missing. Please let me know if something is wrong and isn't working.

Register
Registration is as simple as just inserting a set of data in the users field in the database, and its this data that we are going to use for things like login, setting cookies, giving perks and items, and any extra features you can think of.

Part 1 //Creating MySQL table and fields for user.
You can insert the sql below which will create the table and fields that our data will be going into. This is the basic stuff for a mafia game for now. If you want you can add any extra to better suit your game.
CREATE TABLE users(
--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(25) NOT NULL,
  `password` char(128) NOT NULL,
  `email` varchar(255) NOT NULL,
  `userip` varchar(15) NOT NULL default '',
  `signup_ip` varchar(15) NOT NULL,
  `login_count` int(1) NOT NULL default '0',
  `login_ip` text NOT NULL,
  `money` int(15) NOT NULL default '5000',
  `exp` int(6) NOT NULL default '0',
  `account_type` char(1) NOT NULL default '1',
  `sitestate` char(1) NOT NULL default '0',
  `signup_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
  `rank` char(2) default '0',
  `health` char(3) NOT NULL default '100',
  `points` int(6) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


I hope you have a good understanding of MySQL to be able to know what those values mean and how changing them will affect your game and game-play.

Part 2 // Adding forms.

files we will be working with
application/controllers/home.php(your main controller file)
application/views/includes/Both top and bottom files
application/views/home_view.php
application/views/register_view.php(a page we are going to create to hold our forms for register)
application/models (We will be diving in to models since we are going to be working with database, more on that later)

Lets start with adding forms on the register page
navigate to application/views folder and create a blank page called register_view.php
open the file for editing.

forms with codiniter
Forms work the same in codeigniter as the do anywhere else. Its all html nothing new. What's different is the way you call them in the browser. Lets look at an example
When you want a input form in HTML this is you you call it below.
<input type="text" name="username" value="" id="username"  />

However in codeigniter the have helpers, Helpers help you by making tasks simple and fast. The above code above can be written like this in codeigniter.
$username_field = array('name' => 'username', 'id' => 'username', 'value' => '');
echo form_input($username_field);


I don't know about you but I find this a lot cleaner and simple. I am missing a lot of details on these helpers.Head over to THIS page to learn more about helpers if you haven't already do so. Just like PHP and MySQL you need to read the user guide and understand the basic working of codeigniter which these tutorials easy to follow.
Back on the register page using you knowledge on helpers make your forms. This is how mine looks below

<!-- i have gotten use to puttings things in divs for css and struture -->
<div id="register_main">
	<h1>Register</h1>
	<?php
	// this is a simple variables to hold the already tyepd in data so
	// that they don't have to retype it in if the get something wrong
	if (isset($username_reg)) {$username_reg = $username_reg;
	} else {$username_reg = '';
	}

	if (isset($email_reg)) {$email_reg = $email_reg;
	} else {$email_reg = '';
	}

	if (isset($pass_reg)) {$pass_reg = $pass_reg;
	} else {$pass_reg = '';
	}

	if (isset($pass1_reg)) {$pass1_reg = $pass1_reg;
	} else {$pass1_reg = '';
	}
	// echo out any messages during the registartion process
	if (isset($reg_message))
		echo $reg_message;

	echo br(2);
	//form open which calls to home/register_submit function
	echo form_open("home/register_submit");

	echo form_label('Choose a username', 'username');
	echo br();
	// This is the settings to create my input username filed.
	$username_field = array('name' => 'username', 'id' => 'username', 'value' => $username_reg);
	echo form_input($username_field);

	//using a HTML helper here to help with a break between forms.
	echo br(2);

	echo form_label('Choose a password', 'password');
	echo br();
	// just like input text boxes passwords are be done the same.
	$password_field = array('name' => 'password', 'id' => 'password', 'value' => $pass_reg);
	echo form_password($password_field);

	echo br(2);
	echo form_label('Verify your password', 'password_verify');
	echo br();
	// password confimation to verify the password typed in.
	$password_field_verify = array('name' => 'password2', 'id' => 'password2', 'value' => $pass1_reg);
	echo form_password($password_field_verify);

	echo br(2);
	echo form_label('Enter your Email', 'email');
	echo br();
	// password confimation to verify the password typed in.
	$email_field = array('name' => 'email', 'id' => 'email', 'value' => $email_reg);
	echo form_input($email_field);

	echo br(2);
	// submit all the input to the home / register_submit function in 
	// the home controller
	echo form_submit('submit', 'submit');
	//close the form
	echo form_close();
	?>
</div>


You can now see the use of other helpers. Like the HTML helper to add a break. Again this make things simple like instead of having to have blocks of PHP codes and HTML in between I have one big block of PHP
There shouldn't be anything you don't understand from the code above, but if something just isn't sinking in, please feel free to post below and myself or anyone else will be happy to give you a hand. Make sure you have searched the user guide for help on the topic first.

Part 3 //Viewing the forms, loading helpers
Ok good so far, now you want to view your awesome creation in the browser and see how it looks, first we have to load the helpers and fix up the URL.
If you have been reading the user guide you will see that you have to load a helper to use it. There are two ways to load helpers. Loading it at the top of the page you are using it on (like a includes), or using the autoload.php located in application under config. Open autoload.php and scroll down to helpers tou will see the following

$autoload['helper'] = array();


replace it with

$autoload['helper'] = array('form', 'cookie', 'email', 'url', 'date', 'html');


Don't worry about the other helpers for now, you can see we used the 'html' and the 'form' helper in above. You may have used more. Those helpers we have loaded are going to be the basic helpers we will be using for now.

Once that's done we now need to link the page using controller and view files.
Head over to the controller folder and open home.php and add a new register function, so we can view the register page and another function to we will use to submit our code. So yours should be a bit like 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 Home extends CI_Controller {

	public function index() {
		$data['main_content'] = 'home_view';
		$this -> load -> view('template_view', $data);
	}

	//The main view register function.
	public function register() {
		$data['main_content'] = 'register_view';
		$this -> load -> view('template_view', $data);
	}

	// we are going use this function to submit our variables and 
	// output the results back on the register page so the can see 
	// there mistake and be able to fix it instead of removing all
	// of it.
	public function register_submit() {
		$data['main_content'] = 'register_view';
		$this -> load -> view('template_view', $data);

	}

}

Now for the final bit. We need edit our index_top.php and index_bottom.php located in the views in includes
Open the both index_top and index_bottom and add the following.
The idea is that for the index_top to contain some HTML tags opening and the bottom to include some HTML tags closing so when the are called along with the the other files in view it will all fit together.
In the index_top.php add the following

<!DOCTYPE html>
<head>
	<title>Home</title>
</head>
<body>
<div id="wrap">
 <div id="top">
   Header stuff
 </div>




index_bottom.php

<div id="bottom">
  Footer stuff
</div>
</div>		
</body>
</html>

Now we will go and link the files back in the views folder open home_view.php for editing.
You will see all the stuff welcoming you to codeigniter in there, so delete it all as it wont be needed any more.
Replace it with this, or a way(using the url helper or hardcore HTML code) for you to link to the home controller

Hello and Welcome to Mafia Maina. 

<?php echo anchor('home/login', 'Login', 'title="Login to play"'); ?> / <?php echo anchor('home/register', 'Register', 'title="Register a new account"'); ?>


Nice!! head over to your browsers fix and oops errors and syntax (";") errors you may have other wise you should see this
Posted Image
which leads to this
Posted Image

Fixing the URL.
If everything has worked well and not errors you will notice when you click on the register link you get index.php in the url address.
http://mafiamania.co.uk/index.php/home/register
I don't much care for it but for some people it can be annoying so we will work on removing it. If you try to remove the index.php now you will see a 404 error. So we are going to use .htaccess to archive this. If you don't know about htaccess files, the are just configuration files use to configure web server and one of this includes a url rewrite. head to the root index of your directory where you see application , system and user_guide as a folder if there is no htaccess file you need to create one. Create a blank page called .htaccess no extension.
add the following
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]


If this is done right you can now delete the index.php and it will still work. If you check the anchor link on the page you can see that it still adds the index.php in the url. So we are going to not use anchor(I don't like them any way) and use normal HTML <a></a>.As great as codeigniter is sometimes its nice to do things the normal way. So your register should be something like this
<h1>Hello and Welcome to Mafia Maina. </h1>
<a href="http://mafiamania.co.uk/home/login">Login</a>/ <a href="http://mafiamania.co.uk/home/register">Register</a>


Part 4 // Programming the controller
Head over to the home.php controller. Lets start of by creating out checks to see there are duplicated username and email. For this I created a function to check the database and see if the field already exist and return true or false if the do or do not.
function userdupe($username) {

		$user = $username;

		$sql_check = mysql_query("SELECT username FROM users WHERE username='$user'");

		$num_rows = mysql_num_rows($sql_check);

		if ($num_rows >= 1) {

			return FALSE;

		} else {

			return TRUE;

		}

	}

	function emaildupe($email) {

		$e_mail = $email;

		$sql_check = mysql_query("SELECT email FROM users WHERE email='$e_mail'");

		$num_rows = mysql_num_rows($sql_check);

		if ($num_rows >= 1) {

			return FALSE;

		} else {

			return TRUE;

		}

	}


We are not using a model now because it is just a line to check a database and you can still use PHP/MySQL queries to check the database.
We have worked with helpers now its time to use libraries to help archive awesomeness :). The same way as helpers we need to load the libraries so we can use them. again open the autoload.php file and scroll down to libraries and change the following
$autoload['libraries'] = array();

to
$autoload['libraries'] = array('database', 'session', 'email', 'form_validation', 'javascript', 'parser', 'table', 'pagination', 'typography');


these are libraries that is going to help us soon.
form_validation is one of the most helpful libraries it makes life so easy. If you have read up on it from the user guide you will see that it is used for validation. Also you can see how it is used. We are going to be using it to validate our email, username and password field.

Models
I love working with models mainly in codeigniter because it is the backbone of your whole system. Think of it as the memory part of your system, without this your code will be just a brilliant empty shell full of code with no database(well maybe not haha). Navigate to the models folder and create a file called users_model.php and add the following.

<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Users_model extends CI_Model {

	// function to connect to the database using the database class and 
	// then insert all our data.
	function create_member() {
		// a salt which will help increase security for the password
		// hashed with sha512
		$salt = "**********";
		$password = $this -> input -> post('password');
		$final_password = hash("sha512", "{$salt}.{$password}");

		$new_member_insert_data = array('email' => $this -> input -> post('email'), 'username' => $this -> input -> post('username'), 'password' => $final_password, 'signup_ip' => $this->input->ip_address());

		$insert = $this -> db -> insert('users', $new_member_insert_data);
		return $insert;
	}
}


I normally used to hash my password with MD5 hash because it was simple and my work is just little projects but Atli recently recommended that MD5 has been considered insecure for a while now. I never really looked into it but the more I read about it I found out that there are tons rainbow tables which are not too hard to find but SHA512 part of SHA2 hash family is considered one of the strongest.
Notice the use of the database class, also make not that my salt is *********** it can be any thing you want but make note of the because we are going to be using it in the login.
now head over to your autoload.php and just like the helpers and libraries we have to load our models for use.
scroll down to the models section and change it to something like this.
$autoload['model'] = array('users_model');


Now if we use all what we have learnt and put all of the code together in the register_submit function in the home controller we should get something like 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 Home extends CI_Controller {

	public function index() {
		$data['main_content'] = 'home_view';
		$this -> load -> view('template_view', $data);
	}

	//The main view register function.
	public function register_submit() {
		// take the values from the forms fields and save in variable
		$username_reg = isset($_POST['username']) ? $_POST['username'] : "";
		$email_reg = isset($_POST['email']) ? $_POST['email'] : "";
		$pass_reg = isset($_POST['password']) ? $_POST['password'] : "";
		$pass1_reg = isset($_POST['password2']) ? $_POST['password2'] : "";
		
		$data['username_reg'] = $username_reg;
		$data['email_reg'] = $email_reg;
		$data['pass_reg'] = $pass_reg;
		$data['pass1_reg'] = $pass1_reg;
		// check to see if the username or the email already exist
		// in the database.
		if (($this -> userdupe($username_reg) == TRUE) and ($this -> emaildupe($email_reg) == TRUE)) {

			// the form_validation library. We can set rules 
			// that are followed when processing forms fields.
			$this -> form_validation -> set_rules('email', 'Email Address', 'trim|required|valid_email');
			$this -> form_validation -> set_rules('username', 'username', 'trim|required|min_length[4]|max_length[15]');
			$this -> form_validation -> set_rules('password', 'password', 'trim|required|min_length[4]|max_length[32]');
			$this -> form_validation -> set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
			// if something went wrong with the forum validation pring
			// the error
			if ($this -> form_validation -> run() == FALSE) {

				$data['reg_message'] = 'There is an error with one of the fields';
				$data['main_content'] = 'register_view';
				$this -> load -> view('template_view', $data);

			} else {
				
				/* if nothing went wrong then we are going to go in to the 
				   model and try and insert the data in the database. If 
				   anything went wrong with that then something must be  
				   wrong with the server so try and contract an admin. */
				if ($query = $this -> users_model -> create_member()) {
					$data['reg_message'] = "Hello {$username_reg}, your account is created.";
					$data['main_content'] = 'register_view';
					$this -> load -> view('template_view', $data);

				} else {
					
					$data['reg_message'] = 'Something went wrong contact admin';
					$data['main_content'] = 'register_view';
					$this -> load -> view('template_view', $data);
				}
			}

		} else {
			/* let the user know that the username or the password is
			 * taken and it exists in the database */
			$data['reg_message'] = 'Username or Email Already taken';
			$data['main_content'] = 'register_view';
			$this -> load -> view('template_view', $data);
		}

	}

	// we are going use this function to submit out variables and 
	// output the results back on the register page so the can see 
	// there mistake and be able to fix it instead of removing all
	// of it.
	public function register() {
		$data['main_content'] = 'register_view';
		$this -> load -> view('template_view', $data);

	}

	function userdupe($username) {

		$user = $username;
		$sql_check = mysql_query("SELECT username FROM users WHERE username='$user'");
		$num_rows = mysql_num_rows($sql_check);
		if ($num_rows >= 1) {
			return FALSE;
		} else {
			return TRUE;
		}
	}
	function emaildupe($email) {
		$e_mail = $email;
		$sql_check = mysql_query("SELECT email FROM users WHERE email='$e_mail'");
		$num_rows = mysql_num_rows($sql_check);
		if ($num_rows >= 1) {
			return FALSE;
		} else {
			return TRUE;
		}
	}

}




When everything is done and you go to run it you should see an error like this

Posted Image

Not to worry for security reason we need an encryption key for setting sessions. Click here to get a random generated encryption key. Scroll down until you fine 'CodeIgniter Encryption Keys' and copy any one from the list. Then open your config file and find
$config['encryption_key'] = '';


please your random key like so

$config['encryption_key'] = 'random key in here';


And done... Well done everything is finished on the register side. These are my pics of the register page working.

Posted Image


Posted Image

If you really want to use the anchor helpers for links and stuff and dont want to see the index.php in the url (even if you have the url rewriter when you use the anchor you will see the index.php)you can head over to your config file and find
$config['index_page'] = 'index.php';

and change it to
$config['index_page'] = '';

This way you are use your anchor helper with style

Ok I think that's enough for now. We have ton more to get through. Same as before if you have any errors or if I have missed bits out please let me know to help others.

In the next tutorial we are going to login and see who is online by making users online. See you there
-Denis

Is This A Good Question/Topic? 0
  • +

Replies To: CodeIgniter Text Based Mafia Game || Register part 2

#2 Temp1o1  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 1
  • Joined: 30-October 12

Posted 30 October 2012 - 02:59 AM

There is an error in your SQL code under "Part 1 //Creating MySQL table and fields for user."
The CREATE TABLE users( on line one needs to be removed.

Besides that, nice tutorial so far.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1