post

PHP Build a Webgame Tutorial Part 2

So here the second part finally is!

Hello guys,

Let me introduce you what we will be doing the second part of this tutorial:

  • Create a working login page.
  • Create a working register page.
  • Create a working password lost page.
  • Create a working profile page.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

Files – What do we need to get started ?

If you haven’t done part 1 of this tutorial yet, i recommend to read it first and download the files that are needed from there.

Like i wrote in last tutorial, you should play with your own design cause im not making a design for your game, this is just to explain how to create a full php webgame.
If you prefer to follow my example you could download my styled website.

At this moment there arn’t many members that downloaded it yet so i dont know if this topic is populair or not but i hope that new viewers will register to follow this tutorial and give some feedback or questions 🙂

While doing the whole tutorial we will be start programming in PHP in OOP (Object Orientated Programming) / MVC (Model View Controller)!

Lets get started with part 2!
First we need to think of what we need and want, i prefer to start with the user part where he/she can register and login to view their account.
If i got this, i can easy check without manual inserting rows in the Database, and let my friends test it to see if it all works.
*People other then yourself will find bugs much faster as they don’t know the system like you do.*
After i got the user part i can focus on the rest, how i see it now i will break it apart in parts of:

  1. User Login / Registration / Profile
  2. Unit setup / Market
  3. Building setup / Market
  4. Currency (with Cronjobs or by Date calculation)
  5. Attack / Defend others
  6. Leftovers like HighScore / Page content / Protection / etc.
  7. Backend to let the admin control everything.
  8. Finishing touch.

Lets start creating the controllers for Register Account, Login, Profile and Lost account.
Now lets go to your directory:
C:\xampp\htdocs\{your_folder_name}\application\controllers\” and open the file named “index.php

Here we will put all the handling and variables for the Login and Profile.
The Controllers will send everything to the Views so we keep the HTML code and PHP code clean, as you will see in this tutorial.
The Controllers will call the Models for database connection so we try to keep everything related to the database as well away from the PHP code.
This will give you a nice overview where everything is and easy to expand your code later with new things, or modify it without searching where you wrote the code.

If you downloaded the files of this tutorial, your “index.php” will look like this, it may differ a bit but don’t worry.

index.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Index extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $this->smarty_lib->assign('content', "Welcome to WommBattle!<br/><br/>You need an account to enter the combat<br/>So why dont you create one now?");
    $this->smarty_lib->view("template");
  }

}
?>

The index() function is always the one that will be called if you call the controller (unless defined else in the __construct).
So we check if a form post is send to the page and then parse the data to the index (if we set the form action to this controller).
Type this inside your “function index()” just above the 2 rows that are already there:

$error = "";
if( $this->input->post() ) {
  $this->form_validation->set_rules('username', 'username', 'trim|required|min_length[5]|max_length[25]');
  $this->form_validation->set_rules('password', 'password', 'trim|required');
  if ( $this->form_validation->run() == FALSE ) {
    $error = "<div class='errorMsg'>   ".validation_errors()."</div>";
  } else {
     //We could be logged in, if username and password matches!
  }
}

$this->smarty_lib->assign('loginMessage', $error);


At this point we can allmost log into our website, but before that we need to create an account first, so lets start with the register function so we can actual register and test the login form with a created account.

Create a new controller in “C:\xampp\htdocs\{your_folder_name}\application\controllers\” and name it “register.php

We start with the basic controller code so CodeIgniter can read it, and we can open this page.

register.php

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

class Register extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
   $this->smarty_lib->assign('content', 'The register form will go here.');
   $this->smarty_lib->view("template");
  }

}

?>

Save your script and lets try to reach it, open up your browser and go to: “http://localhost/{your_folder_name}/register/“.
You will notice that the content is changed to: “The register form will go here.

Register created

This is a good start! We will now create the real form.
Lets expand the code in “register.php“:

register.php

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

class Register extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $error = '';
    if( $this->input->post() ) {
      $this->form_validation->set_rules('username', 'username', 'trim|required|min_length[5]|max_length[25]|is_unique[game_users.username]');
      $this->form_validation->set_rules('password', 'password', 'trim|required');
      $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[game_users.email]');

      if ( $this->form_validation->run() == FALSE ) {
        $error = " ".validation_errors()." ";
      } else {
        $error = "<div class='successMsg'>Account created with success!</div>";
      }
    }

    $content = $error.'Register your account and start the battle!<br />
    <br />

    <form method="post">
      <table>
        <tbody>
         <tr>
           <td>Username:</td>
           <td><input name="username" type="text" /></td>
         </tr><tr>
           <td>Email:</td>
           <td><input name="email" type="text" /></td>
         </tr><tr>
           <td>Password:</td>
           <td><input name="password" type="password" /></td>
         </tr><tr>
           <td>&nbsp;</td>
           <td><input type="submit" value="Register!" /></td>
         </tr>
       </tbody>
     </table>
   </form>'
;

    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

Save your work and try it out.
You will see that it will give messages to you when the form fails and says it is created with success when it passes the validation.

Register form created

The validation will check on different things now:

  1. Username is required and need minimal 5 characters and maximal 25 characters also the username must be unique in our database user table.
  2. Password is only required with no further restrictions
  3. Email is required it will check if it is a valid email address and if the email address is unique in our database user table.

Now before we actually add the data to the database we will be making a model first to process it.

Create a new model in “C:\xampp\htdocs\{your_folder_name}\application\models\” and name it “game_users.php” just like how we called our table in the database.

And add this code to it:
game_users.php

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

class Game_users extends CI_Model {

  function __construct() {
    parent::__construct();
  }
}
?>

This is the start of all models you will be creating, just like the controllers.
Now lets add the piece of code that will add the new registered user to the database with the given values!

game_users.php

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

class Game_users extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  function registerUser($_POST) {
    $date = date('Y-m-d H:i:s');
    $ip = "xx.xx.xx.xx";

    //Check valid user IP on diffrent ways
    if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif ( !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    //End IP check

    $data = array(
      'username' => $this->input->post('username'),
      'password' => md5($this->input->post('password')),
      'email' => $this->input->post('email'),
      'started' => '1970-01-01',
      'created' => $date,
      'ip' => $ip
    );

    $query = $this->db->insert("game_users", $data);

    if( $query ) {
      return true;
    }else{
      return false;
    }
  }

}
?>

You can see that i created a new function in the model the function will insert the user given data into the database.
If you do not understand what the function does please read it a few times over or check the CodeIgniter manual on the CodeIgniter website.

Now it is almost working the last thing to do is including the model in the autoload of CodeIgniter!
Go to “C:\xampp\htdocs\{your_folder_name}\application\config\autoload.php” and scroll all the way down to line number 112.

You will see:

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

Change it to:

$autoload['model'] = array('game_users');

Lets try it out by calling the model in our register form!
Open the controller “C:\xampp\htdocs\{your_folder_name}\application\controllers\register.php” and add the following line:


register.php

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

class Register extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $error = '';
    if( $this->input->post() ) {
      $this->form_validation->set_rules('username', 'username', 'trim|required|min_length[5]|max_length[25]|is_unique[game_users.username]');
      $this->form_validation->set_rules('password', 'password', 'trim|required');
      $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[game_users.email]');

      if ($this->form_validation->run() == FALSE){
        $error = " ".validation_errors()." ";
      }else{
        $error = "<div class='successMsg'>Account created with success!</div>";
        $this->game_users->registerUser($this->input->post());
      }
    }
    $content = $error.'Register your account and start the battle!<br/>
    <br/>
    <form method="post">
      <table>
        <tbody>
          <tr>
            <td>Username:</td>
            <td><input name="username" type="text" /></td>
          </tr><tr>
            <td>Email:</td>
            <td><input name="email" type="text" /></td>
          </tr><tr>
            <td>Password:</td>
            <td><input name="password" type="password" /></td>
          </tr><tr>
            <td>&nbsp;</td>
            <td><input type="submit" value="Register!" /></td>
          </tr>
        </tbody>
      </table>
    </form>'
;
    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

That should do the trick! Now try to create your first account.
*Note: you could try to create another one with either the same username or email and you will see it an error message back.*

Using register to fill the database

Ok now we registered our account but we can’t log in!
Let’s finish the login form as well!

We need to expand our “game_users” model to handle the login part.
So open: “C:\xampp\htdocs\{your_folder_name}\application\models\game_users.php” again and add this function.

game_users.php

function loginUser() {
  $data = array(
    'username' => $this->input->post('username'),
    'password' => md5($this->input->post('password'))
  );
  $query = $this->db->get_where("game_users", $data, 1);
  if( $query->num_rows() == 1 ) {
    return true;
  } else {
    return false;
  }
}

This function will tell our controller if the username and password match and return true, or do not match and return false.
Like i just said, it will tell us the match outcome to the controller, so lets open our controller:

C:\xampp\htdocs\{your_folder_name}\application\controllers\index.php

The line:

//We could be logged in!

And replace it with:

if( $this->game_users->loginUser() ) {
  $this->session->set_userdata('game_username', $this->input->post('username'));
}

Now we only need to change our view when we are logged in, i’ve decided to do this in the template_header view.
Later on we will create a library for this, but because we did already pretty much we will try to avoid more files we do not really need yet.

So lets open and change some lines: “C:\xampp\htdocs\{your_folder_name}\application\views\template_header.tpl

{* Menu if logged in *}
{if $this->session->userdata('game_username')}
  Welcome, {$this->session->userdata('game_username')}<br/>
  Lets create some chaos!<br/><br/>
  <a href="{$smarty.const.BASE_URL}logout/">Logout</a>
{else}
  {* Menu if logged out *}
  Are you allready part of the war?<br/>
  Login now!<br/><br/>
  <form action="{$smarty.const.BASE_URL}" method="post">
    username:<br/><input name="username" type="text" /><br/>
    password:<br/><input name="password" type="password" /><br/>
    <input type="reset" value="reset" /> <input name="loginBtn" type="submit" value="login" />
  </form>
  <br/>
  <a href="{$smarty.const.BASE_URL}lost/">lost password</a> | <a href="{$smarty.const.BASE_URL}register/">register</a>
{/if}

As you can see we added a new link called “logout”, because i like to safely close my profile so no one else can play with my game data.

Now save your file and try to login.

Succesfully logged in!

To log out we need a need controller to handle the logout process.
Go to and create: “C:\xampp\htdocs\{your_folder_name}\application\controllers\logout.php


logout.php

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

class Logoutextends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $this->session->sess_destroy();
    $this->load->helper('url');

    redirect(base_url());
  }

}

?>

And we can now even logout!

At this point i will stop with part 2, now it is time for you guy’s to play with your website (mockup) create something nice for the game you’ve got in your mind and try to add more register fields and validation checks!
The next tutorial we will be creating many things for the website like the menu, the contents, and more! so be sure to check back often for updates!

Leave a message or some screenshots please, i would like to see how you guys are doing it or if you are stuck at a point i could help you with.

Good luck and have fun with programming!

 

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

Website finally online

Today we are proud to announce that our new website is finally online!
It took some time to create but we are finally there.
The website is writen in dutch language, we won’t go international with it, but i you have a project you would like us to do, then we can think about it and perhaps do it anyway.

Soon we will continue with My Galaxy Pet again, but for now our website is more important.

http://www.ungahstudios.com

My Galaxy Pet Status

Hey peepz,

Today im happy to announce that we are almost ready for the first alpha stage for My Galaxy Pet.

We only got a few more things to do before we really gonna start an alpha test.

One of those things is finishing the flash template which will load the custom made player into the game.
And the other is that we want a nice looking frontpage for as long as we are developing the website, where you all can view the updates we have made before the website goes online.

The Alpha test will be in a closed group so please don’t ask for an invite.

The website will be found here: http://www.mygalaxypet.com

post

Tutorial HTML – 02 Let’s view some more commands.

Hey people,
In this tutorial we will be using more “Tag’s” like in the first tutorial.
This time we will be using Tag’s that will come handy in webdesign.
If you have question’s or want to know something specific then leave a post and ill awnser it in time.

In this tutorial we will learn:

<ul>
<li>
<table>
<img>
<a href>

Let’s start!
Last tutorial we ended with:

<html>
  <head>
    <title>My first website</title>
  </head>
  <body>
    Wow… My website is the best!
  </body>
</html>

We will use this file again but make it better.

Let’s fill the website with more content, in what Tag we will do this?? …

Body Tag (<BODY></BODY>)

Delete Wow… My website is the best!

And put a table there.
We want a table that contains the: Title/Menu and Information.
3 things so we will need atleast 3 cells.

We want the title on the top offcourse and the menu and information next to eachother.
Add the next code into your Body tag.

<table border="1">
  <tr>
    <td colspan="2">Title comes here.</td>
  </tr><tr>
    <td>Menu comes here.</td>
    <td>Information comes here.</td>
  </tr>
</table>

Save your work and view the file.
So… with a table you can set the interface position of your website.
Every TR Tag is needed for a new row.
And every TD Tag is need for a cell inside the row.
When you got the wanted cells in a row you will need to close the TR Tag and open it again for the next row.
Got everything ready ? then close the Table Tag.

TD colspan=”2″ -> A colspan will melt your cells together here it will melt 2 cells into 1 big cell.

Let’s place something better then current title.
Delete Title comes here. and put:

<img src="http://i372.photobucket.com/albums/oo170/LANTE_17/evil-smiley-face.jpg" />

Save your work and look at your file.
You got an image now… wasn’t that hard was it?

IMG is the Tag with a function “src=” that will find the source of the image (URL).

Lets do the menu, delete Menu comes here and put in place:

<ul>
  <li>Home</li>
  <li>Photo's</li>
  <li>Games</li>
  <li>Websites</li>
</ul>

Save and view your website again.
UL tell’s the browser to sart a list every LI in it will put tekst into that list with a dot in front of it. Make sure you close your Tag’s aswell!

Now we have a nice menu, but can’t click on it.
Change you menu code into this code:

<ul>
  <li><a href="index.html">Home</a></li>
  <li><a href="photos.html">Photos</a></li>
  <li><a href="games.html">Games</a></li>
  <li><a href="websites.html">Websites</a></li>
</ul>

Save again, and view the file.
You will see you can click it now but it will generate errors.
To solve this you will need to make new files again, don’t call them index.html again but like in your menu “photos.html“.
An A Tag has a function HREF this can call objects on the internet like website’s, files, photo’s etc. aswell the A Tag supposed to be closed again! Everything between the A Tag’s will be displayed as an A Tag (Let’s you click on the thing you place between the Tag’s like images or text).

That is it for today!

Mission:

Finish the website further.
Make the menu complete and create other files to link to through the menu.
Make your own title and text.
If you can put it online aswell then do it, i would like to see what you made (and suppose other will like it to).
Everyone likes to see others work.

Good Luck!

post

Tutorial HTML – 01 Let’s get started in webdesign.

Hey people,

I want to learn you guy’s something about HTML (Simple static website’s)
I hope you can learn something from these tutorials

Let’s begin!
Open a editor you will like to use. (Notepad, Notepad++ etc.)
I do NOT recommend Word or Wordpad! Most of the time these will scramble your code.
Notepad is good enough, I myself use Notepad++ this editor will aswell highlight your code for easy use,
this way you will make the most less mistakes.

Lets start with the frist thing you will always need.

<html>
  <head>
    <title></title>
  </head>
  <body>
  </body>
</html>

Explain ?
Everything between <> are called TAG’s these will be reconized by your browser as code.
<HTML> say’s to the browser that you are starting your HTML Code.
<HEAD> This tag will be the first thing that the browser reads.
<TITLE> This must be in your HEAD tag because this need to be readed first in your browser.
<BODY> Here every magic in your website will be placed.

Now save this as index.html.
And double click the file you just created.
If you did everything correctly you will see now an empty website has opend.

You did great if it works and can now edit the file by rightclicking it and select open with. Select here Notepad (or other editor you like to use)

Now change your code to:

<html>
  <head>
    <title>My first website</title>
  </head>
  <body>
    Wow... my first website will be the best!
  </body>
</html>

Now save this again!
If you open it again and look at the titlebar. you will see My first website here now!
We did this between the <TITLE> Tags
You must remember to close all your tag’s like title ( <TITLE> </TITLE> ).
Every tage must be closed with a /
You will see aswell the text Wow… my first website will be the best! in the website.
You just placed your first piece in a website!

For this week we leave it this way. I hope next week to come with a greater post.
If you still having trouble or something isn’t working or you don’t get a point feel free to ask me here.