post

So here the third part finally is!

Hello guys,

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

  • Create a lost password page.
  • Create a memberlist page.
  • Create a shop 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 and 2 of this tutorial yet, i recommend to read those first and download the files that are needed each part.

Like i write in all tutorials, 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.

Lets get started with part 3!
First we need to think of what we need and want, i prefer to continue with the user pages where he/she can retreive a lost password when your user is unable to play.

Lets start creating the controller for Lost account page.
Now lets go to your directory:
C:\xampp\htdocs\{your_folder_name}\application\controllers\” and create a file named “lost.php

Open the file and start editing!

lost.php

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

class Lost extends CI_Controller {

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

  function index() {
  $error = '';
  $content = $error.'Lost your login data?<br/>
  <form method="post">
    <table>
      <tbody>
        <tr>
          <td>Registered email:</td>
          <td><input name="email" type="text" /></td>
        </tr><tr>
          <td>&nbsp;</td>
          <td><input type="submit" value="Get my data!" /></td>
        </tr>
      </tbody>
    </table>
  </form>'
;

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

}
?>

Like part 2 this is the base to view a page, go check it out to see what it looks like.
This won’t be enought to retreive our lost password, for that we need to define some actions.
Lets create the validation and response.

Add these lines under “$error = ”;

lost.php

if ( $this->input->post() ) {
  $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
  if ( $this->form_validation->run() == FALSE ) {
    $error = validation_errors();
  }else{
    $error = "<strong>An email with instructions has been sent to you.</strong>";
  }
}

This piece of code will check if the input from the user is a valid email, else it will show an error.


If you have noticed the message will say that an email has been sent, hope you haven’t checked your mail for 30 minutes or longer… this email won’t be there! so stop looking and start creating the real mail.

replace this line with new code: ‘$error=”An email with instructions has been sent to you.
“;

lost.php

$to = $this->input->post('email');
$subject = "Password recovery for ".BASE_URL;
$headers = 'From: recovery@yourmail.nl' . "\r\n" .
  'Reply-To: no-reply@yourmail.nl' . "\r\n" .
  'X-Mailer: PHP/' . phpversion();
$recoveryLink = md5(date('d-m-Y H:i:s').'-'.$this->config->item('encryption_key'));
$message = "You or someone else has requested a password reset, if it isn't you do nothing else go to this link: ".BASE_URL."lost/reset/".$recoveryLink;
if ( mail($to, $subject, $message, $headers) ) {
  $error = "<strong>An email with instructions has been sent to you.</strong>";
} else {
  $error = "<strong>Sending the mail failed, try again later.</strong>";
}

We just added some basic variables for the email like subject, to address and the content with a link. And finally mail those variables to ourself.
You could try the page again to see if its working. (If you try this on localhost it won’t work unless you have set up a mail server on your computer try it online for direct results).

If you’re able to test this then you will see the mail arrives in you inbox, the only thing that didn’t worked was the link provided by the email! Lets fix this right away!

Add the this code under the index() function

lost.php

function reset() {
  if ( $this->input->post() ) {
    if ( $this->game_users->resetPassword() ) {
      $content = 'Password succesfully reset, login with your new password.';
    } else {
      $content = '<div class='errorMsg'>Password not reset, wrong information given!</div>';
    }
  } else {
  $content = 'Reset your password<br/>
    <form method="post">
      <table>
        <tbody>
          <tr>
            <td>Registered email:</td>
            <td><input name="email" type="text" /></td>
          </tr><tr>
            <td>New password:</td>
            <td><input name="password" type="password" /><input name="indentification" type="hidden" value="'
.$this->uri->segment(3).'" /></td>
          </tr><tr>
            <td>&nbsp;</td>
            <td><input type="submit" value="reset password" /></td>
          </tr>
        </tbody>
      </table>
    </form>'
;

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

Add the next code under the line: if(mail($to, $subject, $message, $headers)) {

lost.php

$this->db->where('email', $to);
$this->db->update('game_users', array("lostpassword" => $recoveryLink));

And finally create a new function in the model named game_users.php

game_users.php

function resetPassword() {
  $data = array(
    'email' => $this->input->post('email'),
    'lostpassword' => $this->input->post('indentification')
  );
  $query = $this->db->get_where("game_users", $data, 1);

  if ( $query->num_rows() == 1 ) {
    $this->db->where($data);
    $this->db->update('game_users', array("lostpassword" => null, "password" => md5($this->input->post('password'))));
    return true;
  }else{
    return false;
  }
}

Try to test if you can reset your password this time. Works ? great! now that this part is done we can create a list of members when we are logged in that we could attack.

To do this we need to create a new controller and call this file ‘userlist.php‘ insert the following code:

userlist.php

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

class Userlist extends CI_Controller {

  function __construct() {
    parent::__construct();
    if ( !$this->session->userdata('game_username') ) {
      header('Location: '.BASE_URL);
    }
  }

  function index() {
    $content = 'Member list.';
    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

Now we can reach the page we should add it to the menu first, to see if we can only reach it when we are logged in!

Open the View named template_header.tpl (application/views/template_header.tpl)
And add the following line just above the the line: <a href='{$smarty.const.BASE_URL}logout/’>Logout</a>

template_header.tpl

<a href="{$smarty.const.BASE_URL}userlist/">Rankinglist</a><br/>

Save your work and test if it works.
If it’s all OK then we can grab some coffee or walk the dog to let our brains and vingers rest for a minute.

Back already? Ok lets continue with the member list.
Open the userlist controller and edit the index() function.
Overwrite “$content = ‘Member list.’;” with the following code.

userlist.php

$content = "Memberlist:";
$content .= "<table cellpadding='0' cellspacing='0' style='width: 100%;'>";
$content .= "<thead><tr><th></th><th>Username:</th><th>Protected?</th><th>Land worth:</th><th>Playing since:</th><th></th></tr></thead><tbody>";

foreach( $this->game_users->getUser() as $member ) {
  $content .= "<tr>";
  $content .= "<td></td>";
  $content .= "<td>".$member->username."</td>";
  $content .= "<td>".(($member->protected == 1) ? "Yes" : "No")."</td>";
  $content .= "<td>".$member->worth."</td>";
  $content .= "<td>".$member->created."</td>";
  $content .= "<td><a>attack!</td></a>";
  $content .= "</tr>";
}
$content .= "</tbody></table>";

Now we have created only the view for the list but haven’t got anything that is selecting all the players yet to display.
To do that we need to add a new model function to the user database.
So lets open the model named ‘game_users.php‘ and add the next function at the bottom:

game_users.php

function getUser($id = null) {
  if ( $id === null ) {
    $this->db->order_by("worth","desc");
    $query = $this->db->get("game_users");
    return $query->result();
  }
}

When all is saved and inserted into the code you could test your website.
Lets see if you can see the member list and the registered members.
And do not attack them yet 😉 we arn’t that far yet!

Only one page left this tutorial the shop page!
Creating pages is very similar to eachother so lets repeat the steps for the memberslist only with the shop this time.

First create a new controller named ‘shop.php‘ and add the following code to it:

shop.php

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

class Shop extends CI_Controller {

  function __construct() {
    parent::__construct();
    if ( !$this->session->userdata('game_username') ) {
      header('Location: '.BASE_URL);
    }
  }

  function index() {
    $content = 'Welcome to the shop.';
    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

Now we can reach the page we should add it to the menu first, to see if we can only reach it when we are logged in!

Open the View named template_header.tpl (application/views/template_header.tpl)
And add the following line just above the the line: <a href='{$smarty.const.BASE_URL}userlist/’>Rankinglist</a>

template_header.tpl

<a href="{$smarty.const.BASE_URL}shop/">Shop</a><br/>

Save your work and test if it works.
If its all OK then we continue creating a new model, name it ‘game_units.php‘.
Insert the following code to get items from the database:

game_units.php

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

class Game_units extends CI_Model {
  function __construct() {
    parent::__construct();
  }

  function getItem($id = null) {
    if ( $id === null ) {
      $this->db->order_by("unitcost","asc");
      $query = $this->db->get("game_units");
      return $query->result();
    }
  }
}
?>

The only thing with new models is, that we need to define them in the configs.
So open up autoload.php found in ‘application/config/autoload.php
and add the new model to this line $autoload[‘model’] = array(‘game_users’);
like this:

autoload.php

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

Now in the shop controller we only need to load the data through the model to the view!
So change the next line ‘$content = ‘Welcome to the shop’;‘ in the controller named ‘shop.php‘ to the following code:

shop.php

$content = "Shop:";
$content .= "<table cellpadding='0' cellspacing='0' style='width: 100%;'>";

foreach( $this->game_units->getItem() as $item ) {
  $content .= "<tr>";
  $content .= "<td>".$item->image."</td>";
  $content .= "<td>".$item->name."</td>";
  $content .= "<td>".$item->attackpoints."</td>";
  $content .= "<td>".$item->defensepoints."</td>";
  $content .= "<td>".$item->healthpoints."</td>";
  $content .= "<td>".$item->unitcost."</td>";
  $content .= "<td><input type='text' /><button>Buy</button></td>";
  $content .= "</tr>";
}
$content .= "</tbody></table>";

Now you can see the shop has some units for sell.
You cannot buy them yet, but soon you will!

This was part 3 of the tutorial.
In the next tutorial we will create some more pages and most likely an inventory to store your units in.
Thank you for reading this part, i hope you liked it.

For those design people out there reading this and think the demo looks ugly, just send me some icons/design’s etc. to make this tutorial better to look at for everyone ;-).

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
——————–

Facebook Comments