Category: framework


Intro to Shield (A Security-Minded Microframework)

August 2nd, 2012 — 5:27pm

Recently I’ve become more interested in something that, despite the wealth of resources out there, still seems to be lacking in a lot of web-based applications – good security. I’m not talking just about the “filter input, escape output” kinds of things. I’m digging a little deeper than that and looking and encryption, hashing, authentication methods and network/server configurations that could open your app wide open to malicious people.

So, in an effort to learn more about the security for PHP based applications, I’ve started up a new project that I hope can serve as a good tool (and maybe a guide) to those looking to create secure applications – the Shield microframework. It’s a small framework in the spirit of Slim framework that has a focus on security aspects and tries to help keep the user’s app a little safer by including things like:

  • Output filtering on all values (preventing XSS)
  • Logging on all actions
  • Input filtering functionality for accessing all superglobal information
  • Uses PHP’s own filtering for data sanitization
  • Encrypted session handling (RIJNDAEL_256/MCRYPT_MODE_CBC, uses IV)
  • Custom cookie handling (including httpOnly)
  • Customized error handling to avoid exposing filesystem information
  • Basic templating/view system
  • IP-based access control

It’s an open source project and it’s already seen some great contributions from people all across the community. I wanted to provide a quick guide to getting started with this handy little framework so you could give it a shot in your own apps.

  • 1. First off, you’ll need to download the framework from github: https://github.com/enygma/shieldframework
  • 2. Once you’ve got it, check out the `app/index.php` file for an example of how to use it (pretty easy, right?)

At its most basic, all you need to do is make a route for the default page (this assumes you’re putting it in that same `app/` directory:

<?php
include_once '../Shield/Shield.php';
$app = new Shield();

$app->get('/',function() use ($app){
    echo 'It works!';
});

$app->run();
?>

That’s really all there is to it…this sets up a route for handling the main page of your app and echoes out the “It works!” message when you hit the page. You might see some other warnings and errors pop up about various settings and directories too. These are there to help you make things more secure, so be sure to make an effort to correct them.

There’s a lot more interesting things you can do with the frame work (it’s all in the README in the checkout) to work with filtering of user input, setting up custom filters, using the View object to add values to and display a rendered view and more.

I hope to make this project even better over time while trying to keep it small and flexible. I’m always looking for new ideas to help make it more secure and user friendly, so if you have any suggestions, please either leave them in the comments or email them over!.

8 comments » | framework, PHP, Shield

Using Models in Fuel

December 23rd, 2010 — 3:31pm

In my previous post on using the Fuel framework I looked at the basics behind getting a site up and running. This time I want to take it a step further and tell you a bit about my experiences getting a Fuel application to talk to a database (in my case MySQL). To learn the process, I fell back on one of my standby sites that’s been rewritten in a few different frameworks now including Solar and a really, really old version of the Zend Framework. It’s not an overly complex site, but the version is starting to show its age. So, I usually take that as an opportunity to rewrite the site in something different, just for the experience.

I’ve already started on a version with the latest download of Fuel and, as a part of it, explored the database model connectivity feature. Now, all of this code is generated from me just looking at the source (since there’s no docs to speak of *cough*) so there’s probably a better way to do some of this that I don’t know. So, lets get started with a basic model.

In my database, I have a few tables – two of them are the “news” and “news_tags” tables. The relationship between the two is news.ID -> news_tags.news_id. Thankfully it works out that this is the default mapping for the relationships between the models. More on that later though…here’s my sample SQL:

create table news (
     news_title VARCHAR(200),
     news_story TEXT,
     date_posted INT,
     ID INT NOT NULL AUTO_INCREMENT,
     PRIMARY KEY(ID)
);
create table news_tags (
     news_id INT,
     tag_name VARCHAR(50),
     ID INT NOT NULL AUTO_INCREMENT,
     PRIMARY KEY(ID)
);

Let’s start with the model files – one for each of the tables. Here’s the basic structure of the file:

<?php
namespace FuelAppModel;
use ActiveRecord;

class News extends ActiveRecord/Model 
{
     // define a sample method
     public function getLatestNews()
     {
          $results = $this->find('all',array(
               'select'        => array('news_title','news_story','date_posted','ID'),
               'limit'         => 10,
               'order'         => array('date_posted','desc')
          ));
          return $results;
     }
}
?>

This is enough for Fuel to now know about the “news” database table. Obviously, you’ll need to have the database connection information correct in your db.php to connect to your instance. A few things to note here – the namespace loads in the base Model functionality so the News class can extend the ActiveRecord bits it needs. The ActiveRecord functionality is contained in a package in the standard Fuel download.

In this model, I’ve defined a simple function to pull out the latest news from our “news” database table. This uses the “find()” method that comes with the ActiveRecord stuff. That first parameter can be one of a few things.

  • An ID number of the record you’re looking for
  • The string “all” to return all matching rows from the where
  • The string “first” that essentially puts a “limit 1″ on the end of the statement

The second parameter sets up the rest of the SQL statement – the “select” array lists the columns to fetch, the “limit” restricts the results and the “order” allows you organize the results by a column. There’s also “offset” and “where” that can help get it more specific. The results are then returned back from the method. If you’re more in the “heavy controller” camp and want to do more complex stuff in there, you can also make a model object inside your controller:

<?php
namespace FuelAppController;

class News extends BaseController
{
     public function action_index()
     {
          $News = new FuelAppModelNews;
          $results = $News->find('all',array(
               'select'        => array('news_title','news_story','date_posted','ID'),
               'limit'         => 10,
               'order'         => array('date_posted','desc')
          ));
     }
}
?>

This essentially does the same thing. Now, lets talk about conventions for models here. If your table name is one word, it’s simple enough – for the “news” table, the model’s name is “News” and the file in /classes/models is “news.php”. For something a bit more complex like “news_tags”, you name the file “newstag.php” and the class “NewsTag”. Note that it looks for the singular version of things – “NewsTag” even though the table is “news_tags”.

Simple, right? Well, if all you need to do is make basic queries and pull that data back out, you’re all set. You can stop here. If, however, you need something a bit more complex like say, table relationships, keep reading. Sure, you can manually join all of your data together, making multiple queries and looping through endless loops to match things up. If you want to save some time you can use the table relationships build into Fuel to do the work for you. There’s currently three different kinds – belongs to, has many, and has one. For the sake of example, I’m only going to show you a “has many” example on our “news” to “news_tags” tables.

Setting up the relationship is super simple. In our News model, we’re going to set a new class property to tell the framework about the relationship:

<?php
namespace FuelAppController

class News extends BaseController
{
     public $has_many = array('news_tags');

     public function getNewsDetail($newsId)
     {
          $results = $this->find($newsId,array('include'=>array('news_tags')));
          return $results;
     }
}
?>

Don’t look at the “find()” call yet, lets concentrate on the new property. This “$has_many” property lets us define the table names we want relations to. By default Fuel tries to look at the other table for a column matching the [current table]_id pattern. Thankfully, we have one of those: the “news” table’s ID relates to “news_tags.news_id”. Works like magic! Additionally you can also define other parameters to manually specify things like the column name to map to.

Okay, let’s look at that find now…we have our relationship defined to the other table, but Fuel knows we might not always want to include that data on every call. To let it know when to pull the news_tags data in, you have to specify it in the “include” parameter of the find() options. When the query runs and the data’s returned, you’ll have the news_tags data in $results->news_tags for your consumption.

There’s one slightly tricky thing that I came across when working with the model features. When it tries to do the join, it looks at the name of the model class it’s trying to use and pulls the name from there. In our case “NewsTag” isn’t the right name for the table. You can however define the table’s name in the $table_name property of the model, but that didn’t seem to cooperate either. It looks like the fault lies in this chunk of code in the “hasmany.php” extension of the ActiveRecord component, around line 212:

<?php
//....
$dest_table = AppInflector::tableize($this->dest_class);
$source_table = AppInflector::tableize($this->source_class);
$source_inst = new $this->source_class;
$dest_inst = new $this->dest_class;
$columns = $dest_inst->get_columns();
//....
?>

In the above snippet it tries to run the “tableize” inflector on the model class’ name to pull out the table. In our case, though, the names don’t match and unfortunately the join() method doesn’t seem to care about the $table_name value and just keeps going on its merry way. It’s a pretty simple fix, thankfully:

<?php
$dest_table = (isset($dest_inst->table_name)) ? $dest_inst->table_name : $dest_table;
?>

With this defined, you can tell it that “$table_name = ‘news_tags’;” and it’ll respect it.

For those used to the more object oriented method of models, there’s also the usual CRUD methods you can use to manipulate the objects:

  • save()
  • update()
  • destroy()
  • and, of course, the find() call

I hope this was helpful and like I said, I’m sure there’s a few things that I didn’t get quite right just because I was fishing through the source to figure them out. I’ve been working on some simple templating for the site, so maybe I’ll write up a post on that next. As always, please point out my mistakes :) That’s the only way to learn!

4 comments » | Development, framework, PHP

A First Look at Fuel

November 24th, 2010 — 11:47pm

UPDATE: I didn’t really mention that Fuel is an open source project. If you want to help out, head over to their github page, fork your own repo and get submitting!

UPDATE UPDATE: I’m not actually affiliated with the Fuel project, just a user. Please direct all suggestions over to their contact form or comment on github. thanks :)

There was an announcement a while back from Phil Sturgeon and a few others (shortly after some issues came to light with a certain other framework) about a new framework they were developing that came to be called Fuel. According to their site, the goal is to be:

a simple, flexible, community driven PHP5 framework. FUEL aims to take the best idea’s from a bunch of frameworks, throw away the “not so good” stuff, and create one awesome framework. It is provided under the terms of an MIT License, which means it’s free to use in your personal, commercial or enterprise projects.

What’s that? Why does the web need another framework? Well, to be honest, it doesn’t – but there is one thing that Fuel has going for it. If you’re one of the many CodeIgniter users out there, you’ll feel almost immediately comfortable with it. Since the devs are CodeIgniter fans themselves, they’ve built a lot of the same feel into how Fuel handles your applications. Unfortunately, there’s not a user guide for it yet, so I figured I’d share some of my experiences with it and maybe get you set down the road to fuel-ing your app (yep, that cheesy pun was required).

So, to get started, here’s some simple installation instructions:

  • Grab the latest source from Github (this will probably change when they make releases)
  • Unpack the files into a web-accessible directory. Mine are in /www/htdocs/fuelapp
  • There’s a /public directory in there – that’s where you need to point the DocumentRoot to
  • Make sure that AllowOverrides is set to use .htaccess and that mod_rewrite is installed and working
  • Move the “example.htaccess” file over to just “.htaccess” to make the rewrites work
  • At this point, when you visit the host for your site, you should get the “Welcome” message
  • Be sure to chmod the app/cache and app/logs directories so that the web server user can read/write to the directories.

That should get you started and have your basic application structure all set to go. In the basic layout, your application will live in the /app directory (makes sense, eh?) with the actual framework living in /core. As far as the three pillars of a MVC framework – they’re in classes/controller, classes/model and views. There’s also a config directory that houses the configuration files for your application.

Let’s start with the controllers – here’s an example snippet from the welcome controller showing you a basic controller structure:

<?php

use FuelController;

class Controller_Welcome extends ControllerBase {
	public function action_hello()
	{
		$this->output = 'Hello '.$this->param('name');
	}
}

This action is called at http://localhost/welcome/hello (obviously replacing the hostname with yours).

If you haven’t seen something like the “use” call before, don’t worry. It’s just namespacing. The framework is PHP 5.3 only, so they can use fun things like namespacing and closures. In the example above, they load the FuelController namespace and extend the ControllerBase by default. There’s some naming conventions to look out for in controllers:

  • Controller class names should be “Controller_*”
  • They should extend ControllerBase
  • Methods should be “action_*”
  • Output pushed to the view belongs in $this->output

Something you don’t see in the above example is how to interact with the view. You’ll need to use the View class to get your data loaded into the right place. Here’s an example of that:

	public function action_index()
	{

		$arr = array(
			'data'		=> 'test data',
			'partial'	=> View::factory('test/partial')->render()
		);

		$this->output = View::factory('test/index',$arr);
		
	}

If you’re quick, you’ve spotted the “partial view” I’ve simulated. By calling that “render” method on the view object, it returns the results as a string that can be appended. The parameter in that “factory” call is the path to the view file. So, the string “test/index” refers to the file /app/views/test/index.php.

There’s already some handy built-in helpers for the framework. It seems like all of them I saw were able to be called statically. So, for example – here’s how you could use the Uri helper:

	public function action_uri()
	{
		$detect = Uri::detect();
		var_dump($detect);
	}

Oh, and one last thing I know some of you are wondering about – database connectivity. Right now, there’s only MySQL connectivity, but I’m sure that’ll change quickly. Here’s a simple database example to get you started:

	public function action_database()
	{

		$db = Database::instance();
		$tables = $db->list_tables();
		var_dump($tables); echo '<br/><br/>';

		$result = $db->query(Database::SELECT,'select * from test_data',false);
		var_dump($result); echo '<br/><br/>';

		var_dump($result->current());
		$result->next();
		var_dump($result->current());

		$this->output = 'test';
	}

Instead of just returning arrays or whatever, the datbase calls by default return iterators. I nice touch in my opinion that could go a long way to help SPL adoption. You can also define an object type on the “query” call that lets you map to and object type.

So far so good…like I said, if you’re a CodeIgniter fan, you’d do well to check out Fuel. It feels more like what CodeIgniter should be when it grows up and joins the rest of the PHP frameworks in the PHP5+ world. I’ve already submitted a small update back to the framework and can already say that the community for it is friendly and open to whatever help they can get. Dan Horrigan, Phil Sturgeon and Jelmer Schreuder are doing a great job so far and I look forward to some more great things to come.

I’m going to continue messing with it and will try to post any fun things I might come across. Feel free to ask me about installation or some of the basics of the framework. I’m happy to share what I know.

Oh, and for those wondering, here’s my sample controller I’ve pulled these samples from:

<?php

use FuelController;

class Controller_Test extends ControllerBase
{

	public function action_index()
	{

		$arr = array(
			'data'		=> 'test data',
			'partial'	=> View::factory('test/partial')->render()
		);

		$this->output = View::factory('test/index',$arr);
		
	}

	public function action_caching()
	{
		Cache::set('mykey','testing');
		$cacheOutput = Cache::get('mykey');

		$this->output = 'cache output: '.$cacheOutput;
		Cache::delete('mykey');

		$this->output.='cache after: '.Cache::get('mykey');
	}

	public function action_uri()
	{
		$detect = Uri::detect();
		var_dump($detect);
	}

	public function action_database()
	{

		$db = Database::instance();
		$tables = $db->list_tables();
		var_dump($tables); echo '<br/><br/>';

		$result = $db->query(Database::SELECT,'select * from test_data',false);
		var_dump($result); echo '<br/><br/>';

		var_dump($result->current());
		$result->next();
		var_dump($result->current());

		$this->output = 'test';
	}

}

?>

12 comments » | framework, PHP

Back to top