Showing posts with label fuse. Show all posts
Showing posts with label fuse. Show all posts

Tuesday, May 13, 2008

CakePHP vs FUSE MVC framework - PHP

Admittedly, I'm a bit biased on the topic since FUSE has been one of my development projects for quite a while, but recently I've been working with CakePHP quite a bit. I enjoy working with Cake, but can't help but think of certain things that FUSE does (in my opinion) a bit better. I've compiled a list of a few items where I think the FUSE MVC Framework has a bit of an advantage on CakePHP.

To be fair, I've also included a few things where FUSE falls short for the moment. Before I begin, I'd also like to add that I think Cake is a great framework, and I've certainly taken cues from my work with Cake to integrate new features into FUSE.

Where FUSE Wins

1. The Query Builder object

Fetching the last 10 active employees in CAKE:
// Controller
$where_conditions[] = 'Employee.active=1';

$this->data['Employees'] = $this->Employee->findAll(
$where_conditions,
null,
null,
null,
10 );

// View
<?php foreach( $this->data['Employees'] as $employee ) {?>
<div>
<?php e($employee['Employees']['first_name'] . ' ' . $employee['Employees']['last_name'] );?>
</div>
<?php } ?>

The same thing in FUSE:
//Controller
$options['limit'] = 10;
$options['where'] = 'employees.active=1';

$this->active_employees = $this->employee->fetch_all( $options );
//View

<{ITERATOR active_employees}>
<div><{first_name}> <{last_name}></div>
<{/ITERATOR}>

The query builder is simply an object that, believe it or not, allows you to build queries. Nearly every method in FUSE that fetches data from the database (including aggregate methods like count_all()) can take a query builder object as one of its $options parameters, and it will apply the customization in that object to the query being executed.
Above is an example of the shorthand syntax for customizing queries. For more complex customization, you can use the SQLQuery object directly, as discussed in the FUSE Wiki

2. FUSE has a real templating system

Iterating through employees in CakePHP
<table>
<?php
foreach( $this->data['Results'] as $result ) {
?>
<tr><td><?php e($result['Employees']['name']);?></td></tr>
<?php
}
?>
</table>

The same thing in FUSE:
<table>
<{ITERATOR employees}>
<tr><td><{name}></td></tr>
<{/ITERATOR}>
</table>

Cake's templating system is too reminiscent of inline PHP, and is sure to send your graphics guy running in the other direction. The FUSE templating system was designed to be extremely simple but incredibly robust, not to mention made to integrate as seamlessly into HTML as possible.

3. Helper methods are easier in FUSE

To generate a dropdown box of all users by first name in Cake:
//Controller
$this->set('users', $this->User->generateList(null, null, null,'{n}.User.id', '{n}.User.first_name'));
// View:
<?php echo $form->input('SomeModel.user_id', array('class'=>'txt', 'type' => 'select')); ?>

The same thing in FUSE:
<{HTML/FormHelper::Select_all( 'User', 'id', 'first_name' )}>


Other compelling reasons to use FUSE over Cake include:
  • FUSE's User authentication and management system is much more intuitive than Cake's ACL implementation.

  • FUSE is also capable of doing nested included tables when fetching data. For example, using the 'include' option to any fetch method, one can account for the scenario where model A is linked to model B, and model B is linked to model C, but you want to select data from A, B, and C. Currently, in CakePHP, you would have to write the query manually. FUSE allows you to do:

    $options['include'] = array( 'modelA', 'modelB', 'modelB.modelC' );
    $iterator = $this->fetch_all( $options );


Where CakePHP Wins

1. CakePHP has a larger user base

Although FUSE has been in development for several years, it was only released to the general public in January of 2008. As a result, its user base is still growing, and CakePHP is a more established framework with more documentation, forums, and third party code dedicated to it. The features of each framework are generally comparable, but the size of the CakePHP community is a huge advantage over FUSE.

2. CakePHP supports database other than mySQL

FUSE 1.1 only has a database object for mySQL, but MSSQL, PostgreSQL and SQLite classes are in the works. Additionally, FUSE will not support using data from multiple databases in one project until 1.1.1.

3. CakePHP has more direct AJAX integration

FUSE supports a variety of AJAX options and makes it very easy to use JQuery, but as of version 1.1, it is not as well integrated as some of Cake's AJAX functionality.

4. Your comment here

I know I'm going to get flamed for leaving the "Where Cake wins" section so short, so I figured I'd offer the opportunity for readers to add their own favorite things about CakePHP by commenting on this entry

Monday, February 18, 2008

MVC and you: Partners in Freedom! (Why developers should be using Model View Controller architecture)

“Model/View/Controller”. To some people, it seems to be nothing but a buzzword – an ambiguous term tossed around development forums and blogs; an idea that’s vague and confusing to anyone who hasn’t actually delved into MVC development. To others, MVC is an obvious way of organizing application structure, and there’s nothing new or exciting about it. And finally there are those of us who stumbled into MVC enlightenment almost by accident and realized, wide-eyed and drop-jawed, that it’s just the “right” way to build applications.

Consider me part of the third group. It wasn’t all that long ago that a Ruby on Rails-enthusiast friend of mine insisted that I start moving toward MVC development for the multitude of PHP projects I’m involved in. He knew I was working on a new PHP framework, and, thankfully, he was persistent in his endeavor to get me to delve into MVC sooner rather than later. My framework had the DB abstraction layer. It had the template system and the form validator and the photo handler and the AJAX module. But what was really missing was a way to tie it all together, and once I got about 20 minutes into MVC, I felt disappointed in myself for not having seen the light earlier. It just makes sense to develop within the MVC structure, and in this article I’m going to first give an introduction to what that structure is, then touch on a few reasons you should be using it, and finally describe a few hurdles you can expect to have to overcome while getting accustomed to it.

What is Model / View / Controller architecture ?

Model/View/Controller, or MVC, is essentially just a way of structuring application code. The idea is not new (it’s been around since 1979 according to Wikipedia), but it’s only happened fairly recently that MVC started to gain widespread acceptance as a viable way to develop web-based applications. A lot of the charge toward MVC-based web development was led by Rails, the Ruby framework that has gained significant momentum in the past few years.

MVC-based web development is based primarily on the “M”, the “V”, and the “C” themselves – the data Models, the presentation (or View), and the interface between them – the real workhorse - the Controller. Each component has a specific role, which I’ve outlined below:

1. The data Model is used to store and retrieve information from the database. In most MVC frameworks, a data model class will exist for each of your database tables. Because the model extends a parent class that has very robust, often clever functionality, you can often gain application-level access to your data (e.g. $employee->first_name) with only a few lines of code. Data models can also be related to one another just as their underlying tables are related, which provides even greater functionality when accessing data across tables (e.g. $company->employees->fetch_all()). This extensible, customizable method for mapping tables to objects allows you to access your database without necessarily having to write SQL. Basic read and write operations are performed through simple class members and methods, and even more complicated queries can be done without having to manually write SQL, though that option is always available.

2. The “View” in Mode/View/Controller is the presentation layer that contains the content the end user will see. In web applications, the view will contain your actual HTML tags. Using the features of the templating system included within the application framework, you can add dynamic functionality to the HTML output while still keeping the application code and the presentation separate. Such a separation allows for cleaner code in both the scripting language and the HTML, and it allows designers and programmers to have more independent control over their respective parts of the application development.

3. The Controller is, as mentioned above, the workhorse of the application. The code in the controller is what’s actually run when a page is loaded, and it handles the “pull and push” – taking data from the database via the data models, passing that data to the view, then rendering the output. In most web-based MVC frameworks, specific URLs are attached to specific controller and methods through a routing file, so, for instance, “/Blog/View/123” might call the view() method of a BlogController object and pass it the id of 123.

Sounds pretty complicated. Why switch from my tried and true methods of inline scripting?

One of the greatest pitfalls a developer can succumb to is using only the language, tools, or methods he or she already knows in order to accomplish a task, rather than seeking out and utilizing the best tools for a particular project. A little bit of time spent overcoming the learning curve can often introduce efficiencies, expand your skillset, and actually save a significant amount of time in the long run.

Many web developers have fallen into the trap of writing what can really be described as a collection of scripts, rather than developing a cohesive application, because the former is the way most of us were introduced to web development. The most common architecture used in, for instance, PHP development, doesn’t really qualify as an architecture at all. Most commonly, PHP-driven sites are comprised of a handful of individual script files that each handle incoming data from web forms or display data pulled from a database, but together lack any kind of standard structure. While this method is quick and dirty and works well for smaller applications, it simply does not lend itself to creating scalable, modular solutions that can be easily maintained and updated even as the size of the application grows.

MVC provides a very structured but very versatile approach to web development, lending itself to being immediately scalable while providing simple interfaces to common functionality. Consider how often your application needs to perform the same types of operations on different data – often this is referred to as CRUD: Create, Read, Update, Delete. Entire websites and web-based applications can often be accurately described as offering only these four features, operating on different data. Without a framework to provide CRUD functionality, the developer has to hand write his INSERT, SELECT, UPDATE, and DELETE queries manually, not to mention coding tedious input validation methods to ensure security and data integrity. However, any MVC framework worth its salt will provide all of that functionality in just a few lines of code. Interested yet?

Ok, you’ve convinced me, but what kind of learning curve can I expect?

The first thing you should know about MVC development is that everything is done through objects, so a solid understanding of object orientation will be extremely helpful in moving forward with any MVC framework. Additionally, HTML output is handled via templates (views) – you will almost never see HTML and PHP in the same file when doing MVC development. Instead, data is passed to the template (sometimes automagically, sometimes manually) and is accessed through special syntax (e.g. <{myvar}>) in the template itself. The separation of application code and presentation sometimes throws people off initially, but the benefits of this method become apparent very quickly. Finally, with MVC, you will not see your .php files in the URI the way you’re used to seeing them. Instead, you define a route that points a URI to a specific method in a specific controller. For instance, mysite.com/BlogEntries/List might call the show_list() method of your BlogEntryController. Not only does this kind of URI routing offer almost limitless customization as to what your URI will look like, it can also be used as an SEO (Search Engine Optimization) tool.


Which framework do you recommend?

Personally, I use FUSE (http://www.phpfuse.net). However, that’s a bit of a shameless plug, since FUSE is my own framework. (See the video below for how you can build a database-driven web app in about 5 minutes :-) Having worked with other frameworks, I honestly believe that FUSE is the easiest MVC framework for PHP, especially as far as initial entry is concerned. There are a slew of other great frameworks available, however, including Cake and Symfony for PHP, Rails for Ruby, Grails for Java, and many, many more.




Friday, January 25, 2008

PHP Security in a shared hosting environment

Since its inception in 1994 as a set of basic development components, PHP has grown into one of the web’s most powerful development engines, having since been installed on literally millions of servers worldwide. And although PHP offers both the versatility and the built-in functionality to run in a reasonably secure fashion, most of those servers are configured in such a way that PHP scripts are at high risk for compromise.

Most PHP-enabled webservers are configured in such a way that the mod_php Apache module is loaded along with Apache itself, thereby allowing HTTP requests to be passed through the PHP engine, which preprocesses the data before it is sent to the client. While this configuration provides a simple, efficient way to get PHP up and running, it raises security issues when working in the most common webserver environment: shared virtual hosting.

Generally, it is unnecessary and wasteful to dedicate an entire server to hosting just one website. Since most sites demand only a small fraction of a server’s available resources, it is more common to have one server be home to a large number of virtual hosts. A virtual host is simply a configuration entry that points requests for a specific URL (for instance, www.google.com) to a particular directory (for instance, /home/www/mydomain.com).

The shared hosting model, though economical, immediately presents a security concern, since the HTTP server (for instance, Apache or Microsoft IIS) needs to have a considerable amount of control over the files and directories that are to be served to the client. If your application offers the ability to upload files posted through web forms, the problem is further compounded since the HTTP server now needs write permission on the destination directory. In the common virtual hosting configuration discussed above, if the HTTP server has write permission to that directory, then any user running a PHP script on that same server can also write to the directory. Obviously, this presents a major security concern. However, there are steps that can be implemented, as a server administrator or as a user, that will eliminate or mitigate the security issues, or at least isolate individual users so that a script exploit on one host cannot easily affect other hosts on the same server. In this article, I will discuss a few methods for more securely configuring PHP, and will offer some security-conscious techniques to use when writing applications. For the sake of convenience, I have grouped the article into three categories: Configuration directives and environment settings that can only be changed by a server administrator, a basic overview of PHP wrapping for the application developer, and general practices for securing PHP code. Even if you are not administrating your own server, I recommend reading through the first section in order to gain an understanding of the problem so that you can know what to expect from your web host. This article makes the assumption that your environment has PHP running on a Linux/Unix variant, with Apache acting as the HTTP server.


From the administrator’s perspective: Configuring your shared PHP environment

As the administrator of a virtual hosting server, you have full control over the HTTP server and the PHP engine, which is the ideal condition for tuning and securing your environment. First, let’s talk about separating the PHP interpreter from the Apache server, so that we negate the file permissions problem discussed above.

The PHP interpreter can be invoked in three different ways: as an Apache module (discussed above), as a CGI binary, and as a CLI. Since the CLI (Command Line Interface) isn’t relevant for serving web pages, I won’t be addressing it in this article. As mentioned above, the most common (and often default) method for invoking PHP is as an Apache module. However, let’s look at an alternative way of invoking PHP – namely, as a CGI binary.

When invoked as a CGI binary, Apache loads the PHP interpreter only when needed, passing necessary input (environment variables, POST data, etc) to the PHP executable, then collecting the output and sending it to the client. In this scenario, the PHP process is separated from the Apache thread, which makes it possible to run the processes as different users, thereby eliminating the permissions problem discussed above. However, by default, PHP is run as the Apache user, so we haven’t yet solved the problem simply by running PHP as a CGI binary. Our next step is to “wrap” PHP so that it is invoked as a user that we specify, not as the Apache user.

Note: Installing PHP as a CGI Binary can introduce other security concerns that are worth being aware of. While PHP is generally secure out of the box, It is advisable to take a look at http://us.php.net/manual/en/security.cgi-bin.php.

While Apache does have its own mechanism, suEXEC, for wrapping CGI programs, I will not be discussing it in this article. Instead, we’re going to look at another open source package: suPHP. Written by Sebastian Marsching, suPHP is a fairly simple Apache module that nicely wraps the PHP binary “in order to change the UID of the process executing the PHP interpreter” (suphp.org).

In my experience, installing suPHP has always been a fairly pleasant (as far as these things go) endeavor. You will need to refer to the suPHP instructions at http://www.suphp.org for installation information for your particular UNIX distribution, but as a lightweight application that makes use of Apache’s dynamic module API, installation of suPHP should be trivial.

There are many articles on using PHP’s ini directives to help lockdown your

server, and although that is not the focus of this article, I would now like to briefly touch on a few directives you should be aware of.

First, be sure to enable PHP’s safe_mode. Although some older applications have trouble running with safe_mode enabled, most have been updated to account for this directive, and its benefits are simply too numerous to ignore, especially if you are not able to use a PHP wrapper such as suPHP. Safe mode will be removed in PHP 6 in favor of alternative methods of implementing file and directory security, but for now, you should leave it enabled.

Next, if you cannot implement suPHP or another PHP wrapper, it’s a good idea to set open_basedir in all of your virtual hosts. Set “php_admin_value open_basedir /path/to/vhost/root” as a directive in your virtual host configuration to ensure that PHP is restricted from reading any files outside of the virtual host’s document root.

Finally, have a look at the disable_functions directive. While you do want to

make sure that your security procedures don’t prevent your users’ applications from running as they should, it’s often the case that few, if any, users will need any of the more potentially hazardous functions such as passthru(), exec(), and shell_exec(). If it is the case that none of your users need these functions, it’s a good idea to disable them.

(Note: In the event that only one user or application needs these functions, suPHP allows you to specify individual php.ini files for specific virtual hosts, which offers a middle ground between allowing these functions globally and restricting applications that need to use them for legitimate purposes.)

From the developer’s perspective: Why do I want a PHP wrapper?

Why do you want suPHP, or a PHP wrapper at all? Let’s look at a very common example – uploading images.

It’s a common condition that an application needs to accept image uploads via the web, and many developers operating in a shared hosting environment have run into the problem where, on the first try, PHP displays a “permission denied” error when trying to move the uploaded file into its destination directory. Our User vs. HTTP server permission problem is back again, where the HTTP server - user “www” or “apache” -does not have the proper permissions to write to a directory owned by the developer’s account. The common solution to this problem is to set the permissions on the destination directory to 777, giving all users system-wide read, write, and execute access. While this does work and your uploads can now flow freely, you’ve just ensured that any other user on the system – there are probably hundreds – could very easily issue an “rm –rf /path/to/your/uploads”, which would quickly and effectively delete everything in the directory. While I personally like to think that there exists camaraderie between users on the same server, this probably isn’t true, and you also have to consider that someone else’s account may have been compromised (probably by a lack of input checking on an upload form – more on that below).

With suPHP (or another PHP wrapper) enabled, you are free to leave your upload destination directories with the same permission as your other web-accessible files – namely that only your user account has write access, and the Apache user can read files and traverse directories. In fact, if your user account is in the same group as the Apache user, you can set these directories to have permission of 750, which is much more restrictive than a wide-open 777.

The primary downside to using a PHP wrapper is that there is in fact a performance hit, since the PHP interpreter has to be invoked for every request, rather than being started as part of the Apache server. However, in my experience, the performance decrease is generally unnoticeable. If your application is extremely performance-critical, you will want to run benchmarks before deciding to use a wrapped PHP environment, or consider graduating to your own dedicated server where you can ensure that only you and your developers have any kind of access to your application files. In the dedicated server scenario, the security concerns of using PHP as an Apache module are largely mitigated. ( Note, however, that if one site on your dedicated server is exploited in a mod_php setup, other sites or files will most likely be vulnerable as well, whereas a server running suPHP with PHP’s safe_mode enabled and open_basedir directive configured will generally be able to jail the attack to one virtual host’s document root)

General practices for PHP application security

At this point, I’d like to briefly go over just a few coding techniques you can use to increase the security of your application. Please understand that this is by no means a comprehensive list, and simply adhering to the suggestions below does not ensure that your application is secure. However, you should make it a point to be security conscious when writing code, rather than trusting your environment to eliminate or mitigate any potential attacks on your application.

1. Sanity-check your data

- This is probably the simplest and most effective way of preventing exploits in your application. Sanity checking just means that if you’re expecting the user to enter a number, make sure you actually received a number. If you’re expecting a string with alphanumeric characters only, verify that that’s what you got. Also, never trust this kind of validation to javascript only, as javascript can easily be disabled on the client side. Finally, never pass user data directly to an SQL query without validating it first. While PHP’s magic_quotes mechanism is great for helping to prevent SQL injection attacks (an attack where a user can enter data in such a way as to run their own arbitrary queries), again you should not rely exclusively on the environment for your application security.

2. Check the type and extension of uploaded files.

- Allowing file uploads is inherently risky, but very often it’s a necessary part of an application. PHP allows you to gain a lot of information about uploaded files before they’re ever written to their final destination, so make use of the information contained in the $_FILES array to ensure that you’re getting the type of file you’re expecting. A basic way of validating the file type is simply to ensure that the extension of the file indicates that it is (or is purported to be) the type of file you’re expecting. A common exploit for upload scripts is for an attacker to upload a malicious PHP script to your site, then browse to the uploaded script to gain control of your files. Even a basic check to make sure that, for instance, only files with a .jpg extension are allowed to be uploaded would prevent this type of exploit. However, I also recommend verifying the MIME type of the file, which is contained in the $_FILES array under the key ‘type’, and will look like: “image/jpeg” or “application/pdf”. Be as restrictive as possible – rather than validating against a list of extensions that are NOT allowed (php, exe, etc), check to make sure that the extension and/or MIME type matches a small group of file types that ARE allowed.

3. Use a .php extension for ALL files with PHP code contained in them.

Often I come across files in PHP projects that have a .inc extension, because they are meant to be included, not browsed to directly from the web. This is a common condition, but there’s a potential security issue here if those files contain any sensitive data (e.g. database passwords). Because .inc files are not parsed by the PHP interpreter, they can be passed directly to the client side if they’re available via a web request, which would allow anyone to read the php code directly. Hopefully the directory these files reside in is denied read access by webserver rules (see below), but even so, there’s no sense in risking an accident where the user ends up being able to browse directly to the file. Use .inc.php.

4. Make use of your webserver’s access control rules (e.g. .htaccess)

- Even if all the php files in your application have a .php extension as discussed in #3, you should still make use of your HTTP server’s access control to prohibit any files in sensitive directories from being served via the web. For instance, if you keep your database passwords in “include/db.inc.php”, this file, and all files in the include/ directory should be prevented from being served via the web. Even though the .php extension will ensure that client-side users can’t read the code if the PHP interpreter is functioning, there is the potential condition that the HTTP server has loaded without the PHP interpreter. Botched upgrades or configuration errors can sometimes cause this condition, and in the event that someone browses to a PHP file without the PHP interpreter ever having been loaded, they will again see the code just as you do when editing the files. In Apache, disabling directory access is usually as simple as creating a file called .htaccess (note the leading period) in the directory, then adding the line: “Deny from All” (no quotes) to that file and saving it.

Friday, December 28, 2007

My favorite web tools of 2007

As the year comes to a close, I thought it would be fitting to reflect on what development tools helped make 2007 easier for me. These tools weren't necessarily created in 2007, but as someone who has a tendency to want to re-invent the wheel, I previously found myself overlooking great third-party products and ideas, so consider this a thank you to those people who contribute great, free code to the community.

1. Scriptaculous (http://script.aculo.us)
Provides: Easy drag and drop, animation, and AJAX functionality

Building on the Prototype Javascript framework, Thomas Fuchs, with the help of a community of open source contributors, has given us an easy-to-use but extremely powerful toolkit for some of the more tedious Javascript tasks we face - namely UI features (e.g. drag and drop) and AJAX functionality. Those of us who have been around long enough to have had to work with positioning and controlling user interface elements know the headaches involved in getting your event handlers to fire as you expect them or tracking the x and y coordinates of the mouse. In fact, I suspect the #1 most common reason for keyboard smashing and monitor punching among developers goes something like "graphic element expanded beyond its container instead of properly wrapping to the next line".
With Scriptaculous, implementing drag and drop, including sortable lists, is about as easy as it can feasibly be, and the AJAX-related classes are a godsend. Even someone with only moderate experience in javascript should be able to implement advanced UI features and AJAX functionality without much trouble. Scriptaculous is well integrated with Ruby on Rails, and I expect that it will soon be driving a lot of the AJAX functionality in my own PHP MVC framework, FUSE

2. The Free Rich Text Editor (http://www.freerichtexteditor.com/)
Provides: a full WYSIWYG editor, a la blogger's "compose" feature

Definitely file this under "things I would NOT like to have to write from scratch"! Released under the Creative Commons License (thankfully), this rich text editor control allows you to easily implement full WYSIWYG functionality into your web application. With a wide range of editing functions, from bulleted lists and visual color selection to drag and drop image placement, it just doesn't get any better than this. A simple .js configuration file provides you with customization options, and once you add in a few tags, you're all set. Custom WYSIWYG in under ten minutes. This one has been integrated into FUSE since the day I found it!




3. Model / View / Controller architecture
Provides: Sanity

Ok, this isn't exactly a "tool", and the idea has certainly been around for a long time (since 1979 according to Wikipedia) , but MVC has finally started to gain real acceptance in the web development community to the point where it's becoming the standard for large scale, web-based applications. Due in some part to the popularization of Ruby on Rails, along with other MVC frameworks like Cake, Symfony(, or FUSE), web developers have finally started realizing that procedural scripting, especially the sort that mixes application code and presentation (e.g. PHP and HTML in the same file), isn't the best method for creating scalable, manageable applications. At this point, most MVC developers will look at you with a true sense of confusion and disappointment if you suggest ANY other way of developing a web app, but it seems that the majority of web programmers are still stuck in the "Chapter 1 of 'Building your first PHP applicatoin'" mentality, mixing procedural code in with HTML and packaging it all up in ugly URLs with long query strings. Get with the program, guys!


So there you have it - some things that helped me keep what's left of my sanity for the past year. I may add to the list if I think of something that really needs to be mentioned, but the three items listed were part of my daily development life in '07, and I suspect that all of them will keep me company for '08 as well.