Page 1

A COMPARATIVE INVESTIGATION INTO WEB DEVELOPMENT FRAMEWORKS ATTILA SZOMOR

University of Abertay Dundee School of Computing & Engineering Systems BSc (Hons) Web Design & Development May 2010


University of Abertay Dundee

Permission to copy

Author: Attila Szomor Title: A comparative investigation into web development frameworks

Degree: BSc (Hons) Web Design & Development Year: 4

(i) I certify that the above mentioned project is my original work (ii) I agree that this dissertation may be reproduced, stored or transmitted, in any form and by any means without the written consent of the undersigned.

Signature ……………………....................................................................

Date …………………………..

ii


Abstract

Decreasing need for web design and development professionals has forced web companies to start using web development frameworks to survive in a fast-changing environment. There are many solutions to choose from and this paper investigates the matter, focusing on Ruby on Rails and its PHP based contenders, with the aim to discuss the advantages and disadvantages of web frameworks, to compare Ruby on Rails with PHP frameworks, and to make recommendations on which web framework for a web developer to choose.

iii


Foreword

Thank you to everyone who helped me through not only the creation of this project, but my four years at University. Special thanks to Malcolm Mactavish for his guidance during all these years. Thanks to him for supervising this project, too. I would also like to thank all my friends who made this experience invaluable and supported me during hard times. Last but not least, I wish to say a big thank you to my parents and other members of my family who were always there for me during these years.

iv


Table of Contents

Introduction......................................................................................................................1 The problem of coding from scratch ..................................................................................2 Creating code ................................................................................................................2 Coding is slow................................................................................................................2 Reusing and managing code ...........................................................................................3 Solution ........................................................................................................................3 Research...........................................................................................................................4 Literature review ...........................................................................................................4 Web development frameworks ..................................................................................5 Model-View-Controller ..........................................................................................5 PHP and its frameworks .........................................................................................6 Ruby and Ruby on Rails ..........................................................................................7 Ruby on Rails vs. PHP .............................................................................................8 Advantages of web frameworks ...............................................................................10 Disadvantages of web frameworks ...........................................................................10 Survey.........................................................................................................................11 Analysis of research .....................................................................................................15 Case study ......................................................................................................................16 Personal experience of the development process ..........................................................16 Discussion of Ruby on Rails tutorial...........................................................................16 Setting up Rails....................................................................................................17 Rails’ database access ..........................................................................................17 Rails’ security ......................................................................................................18 Discussion of CodeIgniter tutorial .............................................................................19 Setting up CodeIgniter .........................................................................................19 CodeIgniter’s database access ..............................................................................20 CodeIgniter’s security ..........................................................................................20 Further analysis of personal experience ........................................................................20

v


Table of Contents (cont'd)

Conclusion ......................................................................................................................22 Web framework recommendation................................................................................22 Future work ................................................................................................................23 Appendices.....................................................................................................................24 Web design and development trends............................................................................25 Salary and job trends ...................................................................................................27 Ruby on Rails tutorial ...................................................................................................29 CodeIgniter tutorial .....................................................................................................44 References......................................................................................................................56

vi


List of Figures

Figure 1.1: Survey respondents' occupation ......................................................................11 Figure 1.2: Web framework publicity ................................................................................12 Figure 1.3: Popularity of web frameworks .........................................................................12 Figure 1.4: User experience working with web frameworks................................................13 Figure 1.5: Web framework security based on user experience ..........................................14 Figure 1.6: User experience of testing web frameworks .....................................................14

vii


Introduction

Web design and development is a fast-moving and constantly changing environment. It has evolved to a state where static pages no longer satisfy the needs of the industry. With Microsoft, Adobe, Google and IBM heavily investing in the PHP based Zend Framework (released in 2007), some experts have prognosticated the slow death of smaller web frameworks. However the rise of free blogging applications made Internet users with average IT skills able to create dynamic web sites easily, even without the use of complicated Content Management Systems (CMS) or other advanced frameworks (Appendix A). Google Trends also suggests that the need for new web sites and also for web designers and developers is reducing and the answer to this problem affecting web professionals isn’t “let’s just make fewer web sites and charge a lot more for every one of them”. Instead, current web developers are in the process of learning to design and create more code and functionality in less time, for reduced costs. To achieve that, they need to reuse existing functions, either by using their own code or developing with the help of web frameworks. Being one of the most popular web frameworks, Ruby on Rails is a possible optio n to use, however there are many close to equivalent solutions available. Technologies based on PHP and Java are the biggest opponents for Ruby on Rails, even though many of them have been influenced by Ruby on Rails and they often use Rails’ methodology as the main part of their system (Appendix A). Although the web design industry is ready to pay Rails developers more than what PHP experts get, it is not guaranteed that Rails will be as prevailing in the industry as PHP or Java. The aim of this project is to discuss the advantages and disadvantages of web frameworks, to compare Ruby on Rails with its PHP contenders, and to make recommendations on which framework for a web developer to choose.

1


The problem of coding from scratch

There are many ways of creating functionality for a web project. Coding from scratch may be a solution, but professional web developers always need to find other ways to make project development time shorter. It is an obvious business need, as the less time professionals spend with coding and testing functionality, the more resources they can use for other parts of projects, such as spending time with the client, designing the web site and the database and doing research. Especially nowadays when project deadlines are getting tighter for web designers and developers.

Creating code To develop functionality the web professional needs to create code. For a new application with unique functionality creating brand new code and documentation is inevitable. After its creation, the developer has to test the code against the application’s needs and will probably find bugs that need to be fixed. After finalizing and testing the code, users of the application will judge it based on its usability. Many of them will provide feedback, too. Although most of this information isn’t part of the code itself, but it is part of the development process and should be stored to facilitate future use.

Coding is slow The most time consuming part of today’s web projects is the development process. When a web designer is busy working on a certain number of projects, accepting a new client will not only depend on the money offered, but also the development time of the project. The most time demanding part of the development process is creating and testing functionality for web applications and it’s impossible to get around it unless the developer has pre-made functions to use or customise for the current project.

2


Simple applications can be developed from scratch relatively fast, but developing and testing a larger project takes a lot longer. Implementing and testing the same functionality in separate web applications shouldn’t take up as much time as doing it the first time.

Reusing and managing code Redeveloping the same functionality for each and every proje ct is inefficient, as it is the recreation of something that has already been achieved within a previous project. Instead, using as much existing code as possible means less new content to create, it reduces development and testing time, and consequently increases productivity. To maximise the amount of code reused, complex code has to be coded in a way that it is reusable for future projects and the code and its documentation is easy to follow. Linear coding makes transparency and building future applications based on the code very hard. Reusable code should allow any developer to understand even the most complex functions of the application and their implementation into new projects should be straightforward.

Solution Web development frameworks are software solutions that help users designing and developing dynamic websites and web applications. The most important feature of these frameworks is the reduced amount of code has to be written by the developer, as libraries of functions are usually provided for web page templates, forms, sessions and database access. Reuse of existing code is also a strong skill of many of these frameworks (Wikipedia 2010a).

3


Research

Today’s dynamic websites are usually made with the help of web development frameworks that include bunches of pre-made code that provide functionality and can be integrated very easily. Web technologies are still under rapid development and the constant changes just keep pushing it forward. The revolution of Web 2.0 and its marks (changing content, interactive information sharing between authors and users, user collaboration through opensource projects) has pushed most web development technologies into one direction. Some of the examples of Web 2.0 are web applications, services, communities, social networks, video sharing sites, wikis and blogs, and most of them use new technologies such as AJAX, the Adobe Flex framework, JavaScript libraries, keyword searches and tag clouds, and are usually created with the help of web frameworks.

Literature review To assist the research process, an overview of related literature was conducted to investigate web frameworks and related methods. A research on Ruby on Rails and PHP frameworks was conducted to evaluate the advantages they provide web developers. As they all implement the Model�View�Controller and Object Orientated methods, a review of these was also inevitable. Most web frameworks are written in programming languages using Object Oriented Programming (OOP). Instead of having loosely written procedures and functions that are meant to serve one purpose, OOP enables the developer to put data and functions into a container. This container is called an object and it enables the programmer to model an application similarly to how things happen in the real world (Wikipedia 2010b). An OOP object often hides its content from other parts of the same program, because its functions are usually irrelevant to the functions of others. One of the advantages of coding with OOP is that it enables the developer to model real world objects to application objects (Eckerson 1993).

4


For example, a bank account has an account number, an account holder, an account type, a balance, etc., so it is obvious to create and use an object that has the same attributes. Another benefit that OOP offers is code reuse. This can be done by creating an object that holds and provides all data centrally (Noabeb 2009).

Web development frameworks The first static websites were made up of hand-coded HTML and didn’t provide dynamic functionality. Modifications to these websites or their content had to be done manually by the developer. This was clearly not ideal and soon dynamic web development languages started to appear. The first few of these were ColdFusion, PHP, ASP and Perl, however these languages weren’t frameworks themselves. Later on actual web frameworks were developed and started to change web design methods again. Some of these frameworks were the Zend Framework, Ruby on Rails and JavaEE. Currently there are numerous web frameworks and CMSs available, the most popular ones are CodeIgniter (PHP programming language), Rails (Ruby), Symfony (PHP), Struts (Java), Django (Phyton) and CakePHP (PHP). These frameworks share many common features such as security, database access, web design templates, JavaScript/AJAX libraries and the ModelView-Controller (MVC) architecture.

Model-View-Controller Ruby on Rails and many of the PHP web frameworks are based on the MVC standards. MVC is a new architecture used in software engineering. Stating new is rather controversial, as the idea of MVC first came up in 1979, however its implementation into web frameworks only happened 15 years later. The architecture consists of models, views and controllers. The model is the representation of the data upon which the application operates. Changing models notify their associated views so they can refresh and display the new content. Most MVC web applications use a database to store data in it, although MVC does not specifically mention the data access layer, because it is encapsulated by the model. Models are not data

5


access objects and they’re more than just data: they enforce all the business rules that apply to their data. The view is responsible for generating the user interface based on the data in the model. Multiple views can exist for a single model for different purposes. The controller receives input from the user and manipulates the model and view objects accordingly. When used in web application development, MVC is often seen where the view is the HTML generated by the application. The controller receives the event from the outside world (normally through the user’s get or post inputs) and decides what to do with it, handing over to the model that contains the business rules and carries out specific tasks, such as processing user registration. Along with the MVC standards, Rails and PHP frameworks also use Active Record as an approach to access data in the model/database. Database objects are wrapped into classes, thus each object is linked to a row i n the table. Every time after creating an object, a new row gets added to the table. Any object loaded gets its information from the database and when an object is updated, the inherited row in the table also gets updated (Thomas and Hansson 2007).

PHP and its frameworks PHP stands for PHP: Hypertext Preprocessor and is a web scripting language allowing HTMLembedding. Based on C, Java and Perl, PHP also provides a couple of unique features , as it was created to allow web developers to design and code dynamic pages quicker. Compared to its original contender ColdFusion, PHP is said to be faster and more efficient to design complex tasks, as it supports creative coding, and is considered to be more stable and less resource-intensive as well (PHP 2010). PHP is so widely used that it has a large community that can provide development support for not just beginners, but professionals, too. A PHP framework includes a vast amount of functions and classes written in PHP that provide a good base for developing dynamic web applications, however PHP frameworks often differ in functionality, directory structure and support.

6


For a web developer, having to code new projects over and over again from scratch is frustrating. Most of these web projects share common features such as file handling, database access, converting and translating text input. A good PHP framework allows developers to aim their focus on business logic, rather than wasting time on re-coding common functions (Brown 2007).

Ruby and Ruby on Rails Ruby is an object-oriented programming language with clean syntax that makes programming elegant and fun. Ruby’s creator Yukihiro Matsumoto successfully combined the features his favourite programming languages into one. Smalltalk's conceptual elegance, Python's easy handling and learning abilities and Perl's pragmatism can all be found in Ruby. Ruby started to become very popular worldwide around 2004 (Ruby 2010). Ruby on Rails is the one that started it all. Since the original release to the latest 2.3.5 version, Rails has been offering unique benefits to web developers such as easy maintenance of databases with migrations and very easy deployment. On the other hand, Rails isn’t the fastest web framework, however most applications won’t ever see the difference (Dewan 2007). Rails is a free, open source Ruby framework for developing web applications that need to access databases. The power in Rails lies in its development speed. According to Rails professionals, Ruby on Rails could make coding up to ten times faster than a typical Java framework and it doesn’t mean that the application would be less in any ways. Part of this feature lies in the Ruby programming language. Many things that are simple to do in Ruby might not be possible to do in other languages and Rails takes full advantage of this. The other reasons why Rails is that easy to develop are hidden behind the guidelines of Ruby: less software and convention over configuration (Hibbs 2005). Less software means that fewer lines of code needed to be written to create an application. Keeping code smaller means faster development and a smaller chance to make errors, which makes Rails code easier to understand, maintain and upgrade. Another attribute of Rails is convention over configuration which means that instead of configuration files, Rails applications use simple programming conventions that allow it to understand everything through reflection and discovery (Hibbs 2007).

7


Ruby on Rails vs. PHP The main goal of this research is a complete evaluation of the differences between Ruby on Rails and PHP, based on recent statements of web developer Steven Bristol, who is a core contributor to the Rails framework, but he has also contributed to several other open source projects as well. When comparing Ruby on Rails with PHP, the first thing to state is that PHP is a programming language, whereas Rails is a framework for writing web applications, so it can’t be an applesto-apples comparison, however PHP frameworks are written in PHP, so the results of the comparison are still valid. There are a lot of PHP web application frameworks, the main ones are the Zend Framework, CakePHP, Symfony and CodeIgniter. Some of these have incorporated methodology from Rails and many other frameworks, such as Java and .NET based frameworks have borrowed a lot from Rails, too. The fact is that Ruby is a very simple language and is easy to code. This means that it supports expressiveness and simplicity: it is easy to create advanced functions in a few lines of code. On the other hand, PHP is a bit too popular, so anyone already working with it might not want to switch over to Rails, as it is possible to do everything in PHP what current web development projects need. In general, PHP applications require less memory to run, so they’re usually easier to deploy than Ruby programs. However, this problem is fixable and should be sorted out very soon by Rails’ creators. Of course, PHP programs will still require less memory, because by default they don’t have the overhead of a web framework. It is possible that PHP code running inside a web framework as advanced as Rails would have similar memory requirements. Ruby on Rails also has migrations which make database changes easier than using any other open source or commercial solution. Scalability of Rails applications is very similar to PHP’s. Although Rails had famous scalability issues in the past such as the rumours heard about Twitter substituting Rails, it wasn’t an issue caused by the Rails framework (Lan 2009). When scaling, both frameworks are just as fast.

8


According to Bristol (2008) Rails is “cooler” than PHP, but he also points out that eventually there will be something even “cooler” than Rails, as this is how computing evolves. Also the result of using Rails (the final product) in general will be a much more advanced and welldesigned application than any other program created by someone who wrote their own web application framework. The following points are the features of any MVC framework such as Rails or CodeIgniter, and they also point out why using an MVC solution is better than a common web framework: 

Code is well encapsulated.

Anyone familiar with MVC standards should be able test and maintain the application.

Very few lines of code written should be able to create a lot of functionality.

However in addition Ruby on Rails includes specific features that are usually not applicable for common web development solutions: 

It is very easy to write a lot of code, to create functions and to test the application in record time.

Database versioning.

A vast amount of helper methods are available for use.

Excellent JavaScript/AJAX support.

Rails functions are very easy to extend.

Built in testing is also included.

Rails has a vibrant community that provides:

o

Many plugins.

o

Lots of blogs, tricks, tips and tutorials.

o

A reasonable amount of professional conferences.

o

A very well tested system.

The basics of Rails are quite easy for a web developer to learn.

9


Advantages of web frameworks Web frameworks contain functions that the web professional should’ve been developing, but never really got around it, such as unit tests, separation of MVC, validation and security. The application is still up for the developer to create, however there’s no need to write templates and basic functions. Web frameworks are similar to having pieces of wood and a toolbox to help assemble a kitchen cupboard. Most web frameworks are easy to learn and their documentation and libraries also make them relatively simple to use. Other advantages are quick development, extendable functions and maintainability. Because these web frameworks follow the MVC pattern, it is easy to keep the logic between functions and other parts of the application. The MVC architecture also separates business logic from presentation and the better URL practice creates search engine friendly applications. The folder structure of web frameworks are usually well organised to enhance development speed and maintainability. SQL knowledge isn’t necessary as the frameworks have built in functions f or database access. Most web frameworks are also secured against many common attacks, such as SQL injection or Cross-Site Scripting. This provides short term user and long term developer satisfaction. There are an endless number of other benefits of using web frameworks, mainly related to development speed, maintainability, application structure and database access behaviour.

Disadvantages of web frameworks There aren’t too many disadvantages of using web frameworks, but in certain cases when the application just doesn’t suit an advanced web framework, using one is not recommended. It doesn’t make sense to create a dynamic application that uses a database when the content of a website almost never changes. In this case a web framework would be a too robust option to run a static application and a simple CMS could be the perfect substitute for the job (Bennett 2006).

10


The opposite of the above is when an open source web framework is just not enough to satisfy the needs of a project. There are special web applications that are better to be created by a custom framework made by a team of developers, such as internet banking solutions and social networking sites.

Survey Further research based on an online questionnaire was conducted to gain information on the current state of web development frameworks, focusing on Ruby on Rails and PHP web frameworks. This survey was aimed at web design and development students and professionals and asked questions regarding seven currently mainstream frameworks, three of them written in Ruby (Rails, Sinatra, Merb) and the other four based on PHP (CodeIgniter, Symfony, CakePHP, Zend Framework). The survey was sent out to Abertay web students and was also advertised on the Internet using Web 2.0 methods of Twitter, Facebook and the author’s blog to collect more information. A remarkable number of 82 responses were collected with the majority of the answers coming from web professionals based not just in the UK, but in countries like the USA, Brazil, South Africa, Japan, Germany, France and many more (Figure 1.1).

Figure 1.1: Survey respondents' occupation

11


More than half of the focus group were professionals working for web design companies or as freelancers. More than one third of the respondents were web students that also helped to expand the sample of the research. As expected, Ruby on Rails proved to have the most publicity compared to its PHP contenders that were one step behind and the survey results also showed that the other two Ruby frameworks (Sinatra and Merb) are nowhere near as well known as Rails or PHP frameworks (Figure 1.2).

Figure 1.2: Web framework publicity

However publicity doesn’t mean popularity, so the survey had to look into that matter, too. Again, the results showed that Ruby frameworks are very popular, with Rails being the dominant framework of the web community (Figure 1.3).

Figure 1.3: Popularity of web frameworks

12


The PHP ones are a bit less valued by the 71 respondents of this question, but still come second to Rails on an average, as the low number of respondents grading Sinatra, Merb and other frameworks caused them to be eliminated from the equation (displayed as faded columns in the figures). To compare these frameworks it is more important to examine actual user experience when working with these frameworks. The answers for the related question of the survey showed that only two frameworks satisfy most developers’ needs and these are CodeIgniter and Ruby on Rails. Also, there were many anonymous respondents praising these two frameworks: “Rails is excellent and unmatched in PHP”, “Rails is fast, secure and scalable”, “Documentation is key, CodeIgniter wins by a mile”, “CodeIgniter is straightforward and easy to use and automates a lot of the basic tasks you need for every development project” and “CodeIgniter is by far the fastest”. The results of this part of the questionnaire displayed a similar pattern, with Symfony getting very good grades, too (Figure 1.4).

Figure 1.4: User experience working with web frameworks

Since user interaction is a functionality included in most Web 2.0 sites, security is more important than ever. Traditionally web sites built on less known languages incorporate better security, as the language’s community is smaller, the general knowledge is lower, and consequently the number and quality of attacks are less dangerous. As the results of the survey suggest it, most web frameworks are well secured, especial ly the one written on the Ruby language (Figure 1.5). This confirms the above statement on web framework security, as Ruby frameworks have smaller communities than PHP ones.

13


Figure 1.5: Web framework security based on user experience

The last thing the survey had a look at was the easiness of testing web frameworks based on only the respondents’ personal experience. As Ruby on Rails is well known of its testability, it’s not a surprise that it is way ahead of the others. PHP frameworks are usually harder to test and the survey displays the same results (Figure 1.6).

Figure 1.6: User experience of testing web frameworks

According to a survey sponsored by the Australian Computer Society, most companies allocate 10% to 40% of their development budgets for testing purposes (Charrett 2007). It is obvious how important the speed and easiness of testing is and Ruby on Rails can be proud of its advantage over other web development frameworks.

14


Analysis of research The fact is that there's nothing the developer can do with Rails and cannot do with PHP frameworks. Applications created with PHP frameworks are a little bit faster, but the difference isn’t visible at smaller projects. Developer productivity is the difference between the two methods. Ruby is loved within its community, as it is so easy and fast to work with. On the other hand, PHP was originally a scripting language and it wasn’t developed to be as user friendly as Ruby. The result of this is that the Ruby on Rails framework minimizes confusion for developers, while PHP frameworks are still scrappy. It is simply easier for developers to work with Rails. This creates some bonus development time that can also be spent on clients or more testing. The number of small start-up companies using Ruby on Rails instead of PHP suggests that Rails is indeed the faster and better option to pick (Schapira 2010). As the survey suggested, choosing a web framework often has more to do with the developer’s feelings about it, however there are clear patterns of Rails being the best framework to test and secure the application with. PHP frameworks providing the best user experience can only be explained by the large number of PHP developers answering the survey’s questions, and again the users’ taste matter a lot. An anonymous comment from a survey respondent also confirms this suggestion: “Ruby hardest to pick up as I am skilled already in PHP”. In case a web developer can’t decide which framework to choose work with, the current trends on the employment market might make up their mind. There’s a high demand for Ruby on Rails developers and their average salaries are also 7% higher than PHP framework developers’ (Appendix B). Although using web frameworks can speed up project development, neither Rails or CodeIgniter will save their users from making mistakes in the added code and bad decisions during project design. Bennett (2006) confirms: “while frameworks do encourage some good programming practice, they can’t replace good programmers or good designers”.

15


Case study

This part of the research, which was performed simultaneously with the first two (literature review and survey), is the evaluation of the development differences of two web applications with similar functionality, one is based on Ruby on Rails and the other one based on CodeIgniter. The Internet domain of www.attilaszomor.com and belonging web space provided by an American web hosting company called HostMonster was bought in January 2010 to specifically allow the use of Rails and PHP at the same domain. The websites developed and stored at this URL will be accessible until at least January 2011. The two web applications designed to be suitable for this project are both simple, secured blogs. This case study provides the reader more information on Ruby on Rails and PHP based frameworks (CodeIgniter being their ambassador), such as looking at the differences between the whole development process, the modified code, database access behaviour and security.

Personal experience of the development process Following the tutorials, the reader can experience developing the applications, such as the author of this document did. It is important not looking at this project as an outsider, but experiencing the whole process as an individual to see and feel the differences between the two development methods. The tutorials were created to hand an opportunity to the reader of this document to go through the creation of simple blog, that displays entries and comments and also lets the user posting comments for each entry. Both applications use a MySQL database to store data and they are secured against the most common security risks.

Discussion of Ruby on Rails tutorial The tutorial attached as Appendix C is a beginner’s guide to installing Ruby on Rails on a specific web server (in this case it’s a Hostmonster account) and developi ng a simple, secured blog without concentrating on too much styling of the website.

16

Very basic


knowledge of HTML and Ruby is essential to understand the development steps of the tutorial. By default Rails includes tools that make web development easier, such as scaffolding that can automatically construct some of the models and views needed for a basic website. Other tools are WEBrick, a simple Ruby web server and Rake, a build system. Together with Rails these tools provide a basic development environment.

Setting up Rails Unfortunately this tutorial is Hostmonster specific and the installation has only been tested on their server, as web spaces that support Ruby on Rails are usually a lot more expensive to buy than those that only support PHP. Other web hosting companies might have different kinds of setups that won’t support this way of installing Rails. There’s one issue that needs to be solved before installing Rails on a Hostmonster account and that’s enabling Secure Shell (SSH) access. The problem with this is that for security reasons the web provider has to conduct an ID check on the user. This involves uploading a copy of a valid ID and the response can take up some time. For this project, let’s assume that it’s already been done and the user can go ahead with installation. The user has to use an SSH client software to access the server and create a Rails application. Creating a default Rails application called “myblog” needs only one command line to be typed in: rails -D -d mysql myblog

Rails automatically creates an application ready to use a MySQL database and displays a welcome screen at the default address of the application. This page provides version information on the application’s tools.

Rails’ database access A database with specific privileges needs to be manually created for the Rails blog. As Ruby on Rails supports having a development, a production and a testing mode as well, it’s a good idea to set them up. Hostmonster doesn’t support the testing database, so that has to be skipped.

17


To make the application able to access the database, its database configuration file has to be updated with appropriate data. Creating tables in the database happens in a special way in Rails. It’s two parts are called scaffolding and migrating, and Rails does it automatically upon two certain SSH command. A table called “Entry” with the fields “title” and “text” would be established by the command below: ./script/generate scaffold Entry title:string text:text

When this command is executed Rails’ scaffolding creates a model called “entry”, a view called “entries”, an application helper, a controller called “entries_controller” and a migration file for the future creation of the table. As it is quite obvious in Rails, scaffolding is the command that creates the MVC structure of the application. To physically create the table for the blog, a migration has to be run: rake db:migrate

But again, Rails does a lot more than expected. It creates fields called the “id”, “title”, “text”, “created_at” and “updated_at”. The bonus fields help Rails and the user to observe the rules of editing content of the database.

Rails’ security Setting up basic authentication for a Rails application is very easy. Modifications have to be made in the Application Controller. Rails is famous of it’s understandable code and the next line, that has to be executed before other functions of the Controller class, is a particular example of this: before_filter :authenticate, :except => [:index, :show]

It means that the “authenticate” function has to run before every function, except “index” and “show”, the functions that only display data, but won’t allow database access for the user. The “authenticate” function itself is also self explanatory: def authenticate authenticate_or_request_with_http_basic do |name, password| name =="admin" && password == "adminsecpass" end end

18


When the function runs it requests basic HTTP authentication and expects the username to be “admin” and the password to be “adminsecpass”. If the user fills the name and passwords in properly, the function allows them go through (run authenticated functions of the controller). Adding simple security to Rails applications is also straightforward, as the default model component of Ruby on Rails (Active Record) secures applications against most types of Cross-Site Scripting (XSS) and SQL injection. It has a built in filter for special SQL characters, which will escape ‘ , ” , the NULL character and line breaks. Escaping HTML entities is also easy, using the “h” function does all the work automatically, so even if malicious comments are posted through one of the forms of the blog, the database and the browser will store and display the same comment, but the HTML source code will be unharmful to the viewer.

Discussion of CodeIgniter tutorial The tutorial attached as Appendix D is a beginner’s guide to installing CodeIgniter and creating a simple, secured blog without putting too much focus on the design part of the website. Basic knowledge of HTML and PHP is needed to understand the development process of the tutorial. As CodeIgniter is a web framework based on the PHP programming language, it is expected to be easily set up on any server that has PHP4/PHP5 and MySQL support, such as Hostmonster’s hosting account where this application was developed at.

Setting up CodeIgniter As most PHP frameworks, CodeIgniter is also well supported because it is written in PHP. To install, the CodeIgniter package needs to be downloaded, unzipped and copied to the web server. The application’s configuration file has to be updated with the URL of the web site and that makes the application viewable right away. Obviously the page it’ll display is a default welcome page, but it is CodeIgniter that’s already working in the background. After creating a new “index” function in a class that extends the “Controlle r” class, the default page displays the function’s content.

19


CodeIgniter’s database access A database with specific privileges needs to be created for CodeIgniter. Although CodeIgniter included a scaffolding tool, for security reasons it is now deprecated and not recommended to use. Instead, the table for the blog application has to be created manually. Most web providers have pre-installed database management tools such as phpMyAdmin to make this process easier. However editing a table is straightforward it leaves room for human errors. To make CodeIgniter aware of the existing database, the “autoload” configuration file has to be updated in a simple way: $autoload['core'] = array('database');

Populationg the database also happens manually, unless the user wants to code a function for it or set up and use the deprecated scaffolding tool.

CodeIgniter’s security There is default security included in CodeIgniter, but it has to be enabled to operate. Turning the automatic XSS filtering on happend by updating the main configuration file: $config['global_xss_filtering'] = TRUE;

There’s also a function called “form_prep” for escaping malicious HTML entities injected through user forms. This disables links and scripts to work on display. Using the above tools secure the application against most attacks, however to also secure it against all SQL injections a common PHP function (“addslashes”) needs to be used. This adds backslashes right in front of all risky characters of the user’s contribution and the application stores it in the database with the added slashes. On display another function (“stripslashes”) needs to be used to remove the previously added characters. This completes the basic security of the blog application.

Further analysis of personal experience There is an issue with Ruby on Rails as setting an application up on a web space can cause a lot of hassle. The web provider might even ask for proof of identification from the web developer and that is just the beginning of a possibly long process.

20


It is clear that CodeIgniter is a lot easier to set up than Rails. PHP enjoys better support on web servers as its community is much bigger than Rails’. In general the Ruby language is a lot easier to use and maintain than PHP, so once the set up process is finished, developing the application is faster with Rails. The two frameworks use different methods for setting up the database and its tables, but there’s no pressure on the user to prefer any of them. Rails’ security is surprisingly perfected to a level that there’s not much room left for improvement. The default security setup of CodeIgniter is satisfactory, however custom changes need to be made to improve it to a level where it can withstand most attacks. Based on the personal experience of development, Ruby on Rails is the better option to choose for any advanced project. Its only drawback is its problematic setup, but considering a lengthy project, it isn’t a major issue. Based on these findings, any unbiased developer should choose Rails as their next web framework to experiment with.

21


Conclusion

The goal of this project was to discuss the advantages and disadvantages of web frameworks, to compare Ruby on Rails with its PHP contenders, and to make recommendations on which framework to choose, which it has fulfilled. To reflect on the results of this research, it can be stated that both Ruby on Rails and PHP web frameworks have similar advantages such as increasing code reuse and decreasing development time, whilst keeping a high standard of code. Ruby on Rails has the fastest development time, it’s very secure and easy to test. PHP frameworks and specifically CodeIgniter are very fast to deploy, they’re well secured, but not that easy to test. It’s easier for a Ruby on Rails developer to find a job and it also pays better than working as a PHP framework professional.

Web framework recommendation To choose a suitable web development framework is solely down to the developer, this research can only give guidelines on the subject. Solely the ease of installation and ability to run on shared hosting would suggest that PHP frameworks are the ones to choose. Minimising the learning curve is also important and if a developer knows PHP well, but doesn’t know Ruby, first they have to experience with the language and can only learn the framework after that. This isn’t ideal, instead sticking to well-known programming languages is vital when developing a project with tight deadlines. Documentation is also an important issue and even though Rails is very well documented, the advantages of the large PHP community are obvious. However the results of this project’s research suggested that Ruby on Rails is a better solution for advanced applications, PHP developers might find it more straightforward not to switch and stick to their favourite programming language to develop with. There are many almost equivalent solutions to Rails and it needs to be emphasised that web frameworks are only tools made for developers and won’t substitute the required knowledge of web development languages.

22


Future work Although this research fulfilled its aim, it is possible to fine tune the project in the near future. Increasing the number of web frameworks tested would provide even more valuable data on their differences. Time limits of this research meant that developing professional applications had to be taken off the agenda, however a future research with more time to develop would allow this project to be taken to the next level. Creating advanced applications that could test most aspects of the participating frameworks would be ideal. It is important to point out that web design and development is indeed a fast-moving environment and the soon expected arrival of the Ruby on Rails 3.0 and CodeIgniter 2.0 might add new possibilities to a future research.

23


Appendices


Appendix A

Web design and development trends

http://www.google.co.uk/tr ends?q=blog&ctab=0&geo=all&date=all&sort=0

http://www.google.co.uk/tr ends?q=web+developer,+web+designer&ctab=0&geo=all&date=all&sort= 0

25


http://www.google.co.uk/tr ends?q=(ruby+on+rails)+|+“RoR”+|+(ruby+rails),+(CodeIgniter)+|+(CakeP HP)+|+(Yii)+|+(Symfony)+|+(Akelos)+|+(Zend+Framework)&ctab=0&geo=all&date=all&sort=0

26


Appendix B

Salary and job trends

http://www.indeed.com/salary?q1=Ruby+on+Rai ls&l1=&q2=PHP+frameworks&l2=

27


http://www.indeed.com/jobtrends?q=Ruby+on+Rails,+PHP+frameworks&l=

28


Appendix C

Ruby on Rails tutorial

How to install Rails and create a simple, secured blog

Author: Attila Szomor Online - Part 1: http://www.attilaszomor.com/blog/2010/05/06/using-the-ruby-on-rails-webframework-how-to-install-rails-and-create-a-simple-blog-part-1/

Online - Part 2: http://www.attilaszomor.com/blog/2010/05/12/using-the-ruby-on-rails-webframework-how-to-install-rails-and-create-a-simple-blog-part-2/

29


1. Introduction This is a beginner’s guide to installing Ruby on Rails and creating a simple, secured blog relatively fast. Ruby on Rails is an open source MVC web application framework based on the Ruby programming language. It’s intended to be used with an agile development methodology that is used by web developers for rapid development. If you’ve not heard about the Agile development or the MVC concept, please read about them first, as you need to know about their basics to be able to understand all parts of this tutorial. Very ba sic knowledge of HTML and Ruby will be needed, too. By default Ruby on Rails includes tools that make web development easier, such as scaffolding that can automatically construct some of the models and views needed for a basic website. Other tools are WEBrick, a simple Ruby web server and Rake, a build system. Together with Rails these tools provide a basic development environment.

Warning! I’ve created this simple blog application on my own web space that’s hosted by Hostmonster, installing and using Ruby on Rails on oth er web hosting provid ers’ web spa ces may (probably) be different and many of them won’t even support Rails. Before you start installing, I need to warn you again, tha t this guide is Hostmonster specific and the installation bit will only work if you have a Hostmonster account. If you’re not with Hostmonster, but you have Ruby on Rails set up on a different host or on your computer, skip steps 1, 2, and 3.

2. Prerequisites If your developing on Hostmonster, you need to have SSH access enabled. Her e’s how to do this on Hostmonster. WEBrick isn’t necessary on a Hostmonster account and you’re not supposed to use it. This is because Hostmonster wants you to develop on their server instead of developing your Ruby on Rails application on your own computer where ther e might not be an Apache install which is pre-configured to use Rails on Hostmonster. “Yay” for the pre-configured Apache, but “Booooooo” for forcing us to develop on the server… Also, you should use MySQL on your Hostmonster account, hopefully this isn’t an issue.

3. Installing Rails on Hostmonster To begin, log into the Hostmonster server using SSH (I use the free PuTTY software as an SSH client, but there are many similar ones on the net to download)...

30


You’ll create a work directory and then cd into it. You can name it whatever you would like, such as “myrails”… mkdir ~/myrails

cd ~/myrails

Create an application called “myblog”. How you create the application depends on what version of Rails is running on the Hostmonster server (currently 2.3.5). To find i t out use the following command… rails -v

If they’re still running Rails 2.3.5, you’ll need to create your application like this… rails -D -d mysql myblog

Next, you’ll need to set up a subdomain for the blog to run on. To do this, log into cPanel on Hostmonster, go to the “Domains” section and click on “Subdomains”, then type “myblog” into the first text box, so your new subdomain would be “myblog.mydomain.com”. Click into the “Document root” field and make sure that it’s automatically changed to “public_html/myblog” (if not, fill it in manually)...

Now click on the “Create” button. You’ve now created a new subdomain, whi ch will contain your Rails application. Next, you’r e going to make your application’s “public” directory be the root directory of that subdomain with the following commands… cd ~/public_html/

rm -r myblog

ln -s $HOME/myrails/myblog/public $HOME/public_ht ml/myblog

If you go to http://myblog.mydomain.com/ you will see the default Ruby on Rails welcome page...

31


However when you click on the “About your application’s environment” link, you’ll probably guess that something’s still not 100% working. The welcome message tells you what to do, but remember, you’re working on a Hostmonster account, so just ignore the first two points the welcome page suggests, skip to the third one and set up your database.

4. Setting up the database Go to the “Databases” section in cPanel and click on “MySQL Databases”. At the bottom of this page, you can to add a MySQL user for Rails to use. Let’s call it “myuser”. Hostmonster prefixes your username to the MySQL user name, so it’ll be something like “username_myuser”. After creating the user, don’t forget to take a note of the password you used. Next, you’re going to create a database at the top of the page. Let’s name it “mydb”. Similarly to the user the database is going to be called “username_mydb”, too. Rails supports having a development and a production mode as well, so you’ll have to create a s econd database. Name this “mydbdev”. Finally, we’re going to link “username_myuser” to the two databases. Select “username_myuser ” and “username_mydb” from the drop down section at the bottom of the page and click on “Add”...

32


At the next page, make sure the “ALL PRIVILEGES” checkbox is checked, then click the “Make changes” button...

Repeat this step with “username_mydbdev” as well. Next you’ll have to edit the database.yml file. Open ~/myrails/myblog/config/database.yml either in Hostmonster’s file editor or in any other applicable software and modify the “development” and “production” sections, adding the username, password, and database that you just created (you only need the change the capital letter bits). You’ll also need to replace the “socket” line with a line specifying the host… development: adapter: mysql encoding: utf8 database: USERNAME_mydbdev pool: 5 username: USERNAME_myuser password: MYUSERPASSWORD host: localhost

production: adapter: mysql encoding: utf8 database: USERNAME_mydb pool: 5 username: USERNAME_myuser password: MYUSERPASSWORD host: localhost

… and just comment out the “test” section like this…

33


#test: #

adapter: mysql

#

encoding: utf8

#

reconnect: false

#

database: myblog_test

#

pool: 5

#

username: root

#

password:

#

socket: /tmp/mysql.sock

5. Creating the database and its tables You’re now going to create a “scaffold”. A scaffold will create a CRUD structure for information, the controllers, the views, and the routes necessary for the blog application. Let’s use SSH again… cd ~/myrails/myblog

./script/generate scaffold Entry title:string text:text

This script just created: 

a model called “entry.rb” (~/myrails/myblog/app/models/)

a new folder and view structure called “entries” (~/myrails/myblog/app/views/entries)

a new layout called “entries.rb.html” (~/myrails/myblog/app/views/layouts/)

a new helper file called “entries_helper.rb” (~/myrails/myblog/app/helpers/)

a new controller called “entries_controller.rb” (~/myrails/myblog/app/controllers/)

and a migration file called something like “20100506122509_create_entries.rb” (~/myrails/myblog/db/migrate/) with the following content…

class CreateEntries < ActiveRecord::Migration def self.up create_table :entries do |t| t.string :title t.text :text

t.timestamps end end

def self.down drop_table :entries

34


end end

… as you can see, the migration file is kind of a database schema. The next thing is to run the migration process… rake db:migrate

… and this will actually set up the database and the “entries” table for you with the “id”, “title”, “text”, “created_at” and “updated_at” fields, so Rails has created a few mor e fields than you originally wanted at the scaffolding process.

This is to aid the application not to run i nto primary key and duplication problems.

6. Setting up rewrite rules Now that the database is set up, you’ll need to add a way for Rails requests to be processed. You have to place Apache rewrite rules into an .htaccess file so that all non-static requests coming into your application are processed through FastCGI, the CGI that Hostmonster uses. To create the .htaccess file, you’ll need to type the following line into your SSH application… touch ~/myrails/myblog/public/.htaccess

The next step is to add the following to the currently empty .htaccess file (you’ll find it here: ~/myrails/myblog/public/)… # General Apache options AddHandler fcgid-script .fcgi RewriteEngine On RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)/!$ $1.html [QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] ErrorDocument 500 "ERROR: app failed to start properly"

… and that’s it! Your Ruby on Rails application is fully functional. You can check this on the welcome page clicking on the “About your application’s environment” link. When clicked, it should display your app’s version info, along with other necessary data.

35


7. Populating the database To use the scaffold function, you’ll need to use the plural of the scaffold name (“entry” -> “entries”). Navigate tohttp://myblog.mydomain.com/entries and here you create, edit, and delete blog entries (along with their associated records). Add a couple of sample entries now.

8. Making “Blog” the default application The aim is to make http://myblog.mydomain.com display the Blog application. To do this, delete the index.html from your public folder… rm ~/myrails/myblog/public/index.html

Now you’r e going to change the routes for your application. Go to the fol lowing line in the routes.rb config file (~/myrails/myblog/config/)… # map.root :controller => "welcome"

… and change it to… map.root :controller => "entries"

Done! Now when you visit http://myblog.mydomain.com, the Blog application shows up by default.

36


9. Setting up basic authentication Right now, anyone can add or edit your blog posts and I’m sure you don’t want that. Let’s go to the ~/myrails/myblog/app/controllers/entries_controller.rb file and add some basic authentication to the “EntryController” class the following way… class EntriesController < ApplicationController

# ADD THIS LINE BELOW

before_filter :authenticate, :except => [:index, :show]

# GET /entries # GET /entries.xml def index @entries = Entry.all

respond_to do |format| format.html # index.html.erb format.xml

{ render :xml => @entries }

end end

***

def destroy @entry = Entry.find(params[:id]) @entry.destroy

respond_to do |format| format.html { redirect_to(entries_url) } format.xml

{ head :ok }

end end

37


# ADD THIS STUFF BELOW

private

def authenticate authenticate_or_request_with_http_basic do |name, password| name =="admin" && password == "adminsecpass" end end

end

Now when anyone tries to add, edit or destroy a blog post, the browser will ask for the username (“admin”) and the password (“adminsecpass”)...

10. Adding comments to the blog You’ll have to use SSH and scaffolding again (explained in Part 1 of the tutorial)… cd ~/myrails/myblog

./script/generate scaffold Comment entry_id:integer text:text author:string

… and as usual, the next thing is to run the migration process… rake db:migrate

… and this will create the “comments” table in the database…

38


… and an “entry.rb” model file (… plus many more files we don’t need to care about now). Let’s edit the “entry.rb” model file and add some validation and state that an entry can have many comments… class Entry < ActiveRecord::Base validates_presence_of :title, :text has_many :comments end

… and also edit the “comment.rb” model file to state that a comment always belongs to an entry… class Comment < ActiveRecord::Base belongs_to :entry end

The next thing you’ll do is that you change the “routes.rb” file in the ~/myrails/myblog/config folder. You’ll need to edit this bit at the top… ActionController::Routing::Routes.draw do |map| map.resources :comments

map.resources :entries

… and change it to… ActionController::Routing::Routes.draw do |map| map.resources :entries, :has_many => :comments

What you want to do now is to display comments for the articles. It is obvious that you’ll have to edit the entry show view (~/myrails/myblog/app/views/entries/show.html.erb) adding some HTML and a Rails partial to it… <h2>Comments</h2> <div id="comments"> <%= render :partial => @entry.comments %> </div>

To make the comment partial display, you need to create a new comments view called “_comment.html.erb” (~/myrails/myblog/app/views/comments) and add the following content to it… <% div_for comment do %> <p> Comment posted <%= time_ago_in_words(comment.created_at) %> ago <br />

39


<%= h(comment.text) %> </p> <% end %>

Now when you navigate to an entry page, you can see the “Comments” title appearing, but of course as no one has posted a comment yet, there are no comments underneath…

The next step is to add a comment for m to the entry pages…

Using Rails this is how you add it (to “_comment.html.erb”) … <% form_for [@entry, Comment.new] do |f| %> <p> <%= f.label :text, "Write comment here:" %><br /> <%= f.text_area :text %> </p> <p><%= f.submit "Submit" %></p> <% end %>

40


You’ll have to make this form work now. Go to the comments controller that the comment scaffold created (~/myrails/myblog/app/controllers/comments_controller.rb), delete all content of the CommentsController class (but leave the class itself) and add the following… def create @entry = Entry.find(params[:entry_id]) @comment = @entry.comments.create(params[:comment]) redirect_to @entry end

Now if you submit a comment, the page will refresh and the comment will be displayed above the form…

11. Adding simple security to the application The default model component of Ruby on Rails (Active Record) secures applications against most types of SQL injection. Rails has a built in filter for special SQL characters, which will es cape ‘ , ” , the NULL character and line breaks. Where you used the “find()” or “create()” functions in your application, Rails escapes these special characters, so SQL injection can’t happen, for example… @comment = @entry.comments.create(params[:comment])

Wherever you used the Rails function “h()” (e.g. in “_comment.html.erb”) your application is also escaping inappropriate HTML to avoid cross-site scripting (XSS) and CSS injection on display… <%= h(comment.text) %>

So when a hacker enters the following comment… SQL injection: '); DROP TABLE users; <a href=" http://www.yoursite.com/yourfolder/ index.php/blog">Back to blog</a>

41


<script>var i=9;</script><div style="background:url('javascript:alert(1)')">

… the database and the browser will store and display the same comment, but the HTML code will be changed to… SQL injection: '); DROP TABLE users; &lt;a href=&quot; http://www.yoursite.com/yourfolder/ index.php/blog&quot;&gt;Back to blog&lt;/a&gt; &lt;script&gt;var i=9;&lt;/script&gt;&lt;div style=&quot;background:url('javascript:alert(1)')&quot;&gt;

Also, the Ruby on Rails website includes a brilliant document on securing Rails applica tions that web developers can use for their custom security needs.

12. Adding header and footer to the view Your application currently has two views: entries and comments. You’r e going to create an entirely new view for all parts of the blog and the two original views won’t be needed any more. You can delete them, if you want to. Now create a new view file called “application.html.erb” in ~/myrails/myblog/app/views/layouts/ and place some sample HTML into it adding… <%= yield %>

… wher e the changeable content of the application would go, such as… <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<head> <title>MyBlog - Ruby on Rails application</title> <!-- Rails scaffolding CSS --> <%= stylesheet_link_tag 'scaffold' %> <!-- Your custom CSS for blog --> <%= stylesheet_link_tag 'myblog_style' %> </head>

<body>

<h1>Welcome to MyBlog!</h1>

<%= yield %>

42


</body> </html>

Check out how your application looks now, and create a â&#x20AC;&#x153;myblog_sty le.cssâ&#x20AC;? file to edit your applications look. If necessary, you can delete the line linking to the scaffolding style in the view.

Check out the working application here.

43


Appendix D

CodeIgniter tutorial

How to create a simple, secured blog in 30 minutes

Author: Attila Szomor Online: http://www.attilaszomor.com/blog/2010/05/04/using-the-codeigniter-php-web-frameworksetting-up-a-simple-secured-blog-in-30-minutes/

44


1. Introduction This is a beginner’s guide to installing CodeIgniter and creating a simple, secured blog in about 30 minutes. CodeIgniter is an open source MVC web application framework with a very small footprint. Its aim is to enable developing projects much faster than writing code from scratch, by providing a set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. If you’ve not heard about the MVC concept, please read about it first, as you need to know about its basics to be able to understand all parts of this tutorial. Basic knowledge of HTML and PHP will be needed, too.

Although I’ve created this simple blog application on my own web space that’s hosted by Hostmonster, using other web hosting companies’ solutions shouldn’t be a problem, if they have PHP and MySQL installed on thei r servers.

2. Installation Download CodeIgniter from their website. Unzip it. Create a folder named “yourfolder” (or whatever you want to call it) on your web space inside any www or public_html folder an d upload the CodeIgniter folders and files into this folder.

Open the application/config/config.php file with a text editor (I use Notepad++) and set your base URL (e.g. www.yoursite.com/yourfolder – “yoursite.com” being your domain and “yourfolder” is the folder you just uploaded the CodeIgniter files to). Open the application/config/database.php file with a text editor and set your database settings. Most web hosts provide users with “How to set up your database” guides, if you’re not sure how to do this, look them up on your host’s website.

3. Creating the “blog” controller Create a file called blog.php in the “controllers” folder. this is going to contain your first custom CodeIgniter controller, called “Blog”. Add the “index ” function to the controller to test it is working… <?php class Blog extends Controller { function index() { echo "hey!"; } }

45


?>

Now www.yoursite.com/yourfolder/index.php/blog displays… hey!

Go, check it out, it should look something like this…

4. Making “blog” the default application The “blog” controller is now working, howeverwww.yoursite.com/yourfolder/ still displays CodeIgniter’s default welcome screen, so let’s change this to your blog’s home page in config/routes.php! Change the following line… $route['default_controller'] = "welcome";

to… $route['default_controller'] = "blog";

Now www.yoursite.com/yourfolder/ displays the “hey!” message, too…

5. Creating the “blog” view Create a file called blog_view.php in the “views” folder. Add a few lines of simple HTML (html -head-body) code to blog_view.php, this is still easy enough. Add the following line to the “index” function created in Step 2 and delete the “echo” line… $this->load->view('blog_view.php', $data);

… now www.yoursite.com/yourfolder/ displays the HTML you just added to blog_view.php, but it also displays a PHP warning, as the “$data” variable doesn’t exist yet. All in all though, your first custom view is being displayed…

46


6. Creating dynamic content Change the content of the “index” function in blog.php to the following… $data['title'] = "Blog"; $data['h1'] = "Welcome to my blog!"; $data['list'] = array('first', 'second', 'third'); $this->load->view('blog_view.php', $data);

Add the following PHP code to blog_view.php: E.g. Create the title in the head… <title><?php echo $title; ?></title>

… and an ordered list in the body… <ol> <?php foreach($list as $item): ?> <li> <?php echo $item; ?> </li> <?php endforeach; ?> </ol>

www.yoursite.com/yourfolder/ now displays your dynamic title and list…

47


7. Database setup Create a database and a user for it. It is pretty straightforward on Hostmonster, other providers may ask you to do it differently, so again, if you’re not sure, check their website for guides. Add two tables (“entries” and “comments”) to the database and the fields “id”, “title”, “text” for the entries table, and “id”, “entry_id”, “text”, “author” for the comments table. Set auto increment to TRUE for both of the “id”-s (using phpMyAdmin is good enough to modify the database, but you can use different methods, as well). Edit the autoload.php config file, to make CodeIgniter auto load the database, otherwise it won’t work… $autoload['core'] = array('database');

Populate your database with some test data. You could use phpMyAdmin again, or try CodeIgniter’s scaffolding function, but you have to set scaffolding up first! Warning: scaffolding must only be used during development!

8. Setup blog to display data from database Add a get data query to the “index” function in blog.php (anywhere before the last line of the function), this’ll get all the data from the “entries” table… $data['query'] = $this->db->get('entries');

Change the PHP foreach section found in blog_view.php to the following… <?php foreach($query->result() as $row): ?> <h3><?php echo $row->title ?></h3> <p><?php echo $row->text ?></p> <hr /> <?php endforeach; ?>

Now www.yoursite.com/yourfolder/ displays all the sample blog entries with horizontal lines separating them…

48


9. Adding links to a comments page Create a link in blog_view.php using CodeIgniter’s anchor function and place it into the foreach function, above the horizontal ruler… <p><?php echo anchor('blog/comments/'.$row->id, 'Comments'); ?></p>

The anchor function makes creating HTML anchors faster and easier. Great, but it won’t work yet. First you’ll have to call the “url” helper to make it work. It’ll be done in the nex t step.

10. Creating the comments page (displaying and submitting comments) You need to load CodeIgniter’s “url” and “form” helpers through blog.php, inside a new function called “Blog”. Place it to the top of the “Blog” class… function Blog() { parent::Controller(); $this->load->helper('url'); $this->load->helper('form'); }

The “Comments” links will appear from now on…

49


Let’s create a “comments” function in the “Blog” class and add the following to it… $data['title'] = "Comments"; $data['h1'] = "Comments"; $this->load->view('comment_view.php', $data);

To display the comments, a new view is needed to be created, let’s call it comment_view.php. Create it now in the views folder and add the usual sample HTML code to it. Insert CodeIgniter’s “form_open” and “form_hidden” functions into the body section of the new comment_view.php file… <?php echo form_open('blog/comment_insert'); ?> <?php echo form_hidden('entry_id', $this->uri->segment(3)); ?>

Add a tex t area, an author field and a submit button below to finish off the comment for m you just started creating… <p><textarea name="text" rows="10"></textarea></p> <p><input type="text" name="author" /></textarea></p> <p><input type="submit" value="Submit" /></textarea></p>

… so it will look like this…

50


A function called “comment_insert” needs to be created in blog.php for CodeIgniter’s “form_open” to run it. What the following code does is that it inserts the comment into the “comments” table of the database and redirects the browser to the current comment page, to virtually refresh it. Add this to the “comment_insert” function now… $this->db->insert('comments', $_POST); redirect('blog/comments/'.$_POST['entry_id']);

Add the following two lines to the “comments” func tion (before the last line of the function) to display only the related comments for each blog entry… $this->db->where('entry_id', $this->uri->segment(3)); $data['query'] = $this->db->get('comments');

Edit comment_view.php to display only the comments related to the blog posts and also add a back link to the blog… <?php foreach($query->result() as $row): ?> <p><?php echo $row->author ?></p> <p><?php echo $row->text ?></p> <hr /> <?php endforeach; ?> <p><?php echo anchor('blog', 'Back to blog'); ?></p>

And that’s it! Check if it’s working or not. When you add a couple of comments, it should look similar to this…

51


You should now have a simple blog, that is working properly. It is possible to view blog entries and to comment on them. If you’d like to add bonus functionalities to your application, continue the tutorial below!

11. Adding style, header and footer to all views Create a header.php and footer.php file in the views folder with obvious content in them. Edit the “index” function found in blog.php to load the header before blog_view.php and the footer after it… $this->load->view('header.php'); $this->load->view('blog_view.php', $data); $this->load->view('footer.php');

Edit the “comments” function the same way to create the same look and delete the now unnecessary HTML bits from “blog_view.php” and “comment_view.php”.

12. Displaying “no comments” message if there’s no comment for a blog post Wrap the “foreach” function in comment_view.php into a PHP “if” function the following way… <?php if ($query->num_rows() > 0): ?> *** /* The original foreach function must be placed here. */ *** <?php else: ?> <p>No comment has been posted for this blog entry.</p> <hr /> <?php endif; ?>

… and a no comment page will look like this…

52


13. Adding simple security to the comments page First, you have to turn CodeIgniter’s automatic XSS filter on. It activates every time when GET, POST or COOKIE data is encountered and it stops malicious scripts to be posted in comments. Let’s set it to TRUE in config/config.php… $config['global_xss_filtering'] = TRUE;

To escape inappropriate HTML inserted into comments, you need to add the “for m_pr ep” f unction to comment_view.php the following way… <p><?php echo form_prep($row->author) ?></p> <p><?php echo form_prep($row->text) ?></p>

This will stop links and other malicious stuff appearing in comments…

To also secure the blog against common SQL injection techniques, you must: a.

Edit the “comment_insert” function in blog.php, using the “addslashes” PHP function and creating an “insert_data” array to store the “post” variables for the function…

53


$post_id = addslashes($_POST['entry_id']); $post_text = addslashes($_POST['text']); $post_author = addslashes($_POST['author']); $insert_data = array('entry_id' => $post_id, 'text' => $post_text, 'author' => $post_author); $this->db->insert('comments', $insert_data);

b.

Edit “comment_view.php”, using the “stripslashes” PHP function to remove added slashes at display… <p><?php echo stripslashes(form_prep($row->author)) ?></p> <p><?php echo stripslashes(form_prep($row->text)) ?></p>

After all these modifications if a malicious comment is entered, e.g.: SQL injection: '); DROP TABLE users; <a href=" http://www.yoursite.com/yourfolder/ index.php/blog">Back to blog</a> <script>var i=9;</script>

… it’ll be displayed like this…

… and the database will store it as… SQL injection: \'); DROP TABLE users; <a href=\" http://www.yoursite.com/yourfolder/ index.php/blog\">Back to blog</a> [removed]var i=9;[removed]

… so your function is secured against most SQL injection attacks. Check out the working application here .

54


References


References

Bennett, J. 2006. Let’s talk about framewo rks: Wh en fra mewo rks a ren’t right [online]. Available from: http://www.b-list.org/weblog/2006/jun/10/lets -talk-about-frameworks-when-frameworks-arent/ [Accessed 27 April 2010]

Bristol, S. 2008. Comparing PHP to Ruby on Rails. [online]. Available from: http://b.lesseverything.com/2008/8/25/comparing-php-to-ruby-on-rails [Accessed 12 January 2010]

Brown, N. S. H. 2007. PHP vs. Ruby on Rails. An evolutionary story of a Web Developer and his tools. [online]. Available from: http://www.oreillynet.com/ruby/blog/2007/01/php_vs_ruby_on_rails_an_evolu.html [Accessed 21 February 2010]

Dewan, R. 2007. What web framework should you use? [online]. Available from: http://blogs.srijan.in/2007/12/26/what-web-framework-should-you-use/ [Accessed 6 March 2010]

Charrett, A. M. 2007. How low do you go? [online]. Available from: http://mavericktester.com/howlow-do-you-go [Accessed 13 April 2010]

Eckerson, W. 1993. Smack-dab in the Middle. Network Wo rld [online] Jun 21: p.45. Available from: http://books.google.com/books?id=dDgEAAAAMBAJ&lpg=PA76&dq=computer%20ethics%20universit y%20students&lr=&as_brr=1&pg=PA1 #v=onepage&q=computer%20ethics%20university%2 0students &f=false [Accessed 12 January 2010]

Hibbs, C. 2005. Rolling with Ruby on Rails. [online]. Available from: http://oreilly.com/ruby/archive/rails.html [Accessed 11 January 2010]

Hibbs, C. 2007. What is Ruby on Rails. [online]. Available from: http://onlamp.com/pub/a/onlamp/2005/10/13/what_is_rails.html [Accessed 11 January 2010]

Lan, I. 2009. Twitter, Ruby on Rails, Scala and people who don’t RTFA. [online]. Available from: http://ikaisays.com/2009/04/02/twitter-ruby-on-rails-scala-and-people-who-dont-r tfa/ [Accessed 12 January 2010]

Noabeb, J. L. 2009. Object O riented Progra mming - The beginning. [online]. Available from: http://www.webreferenc e.com/programming/php/OOP_01/index.html [Accessed 12 January 2010]

PHP. 2010. [online]. Available from: http://uk3.php.net/ [Accessed 11 January 2010]

56


Ruby. 2010. About Ruby. [online]. Available from: http://www.ruby-lang.org/en/about/ [Accessed 11 January 2010]

Schapira, A. 2010. Ruby vs. PHP for non-techs (also Rails vs. CakePHP). [online]. Available from: http://blog.pomelollc.com/ruby-vs-php-for-non-techs-also-rails-vs-cakep [Accessed 16 May 2010]

Thomas, D. and Hansson, D. H. 2007. Agile Web Developmen t with Rails. 2nd ed. USA: The Pragmatic Bookshelf

Wikipedia. 2010a. Web application framework. [online]. Available from: http://en.wikipedia.org/wiki/Web_application_framework [Accessed 11 January 2010]

Wikipedia. 2010b. Object oriented progra mming. [online]. Available from: http://en.wikipedia.org/wiki/Object-oriented_programming [Accessed 11 January 2010]

57

A comparative investigation into web development frameworks  
A comparative investigation into web development frameworks  

Honours project dissertation

Advertisement