Category: Everything

How not to do a CI controller? – Tips to develop CodeIgniter Controllers

Posted by – December 11, 2011

I cam across a post that was actually a small tutorial on CodeIgniter. The tutorial had what ever it requires to write a basic controller. I am picking up the same post and adding my comments to the post.

The original post – http://phpmaster.com/untangling-mvc-with-codeigniter/

The controller

<?php
public function index() {
    $this->load->helper("form");
    $this->load->library("form_validation");

    $this->form_validation->set_rules("first", "First Name",
        "required");
    $this->form_validation->set_rules("last", "Last Name",
        "required");
    $this->form_validation->set_rules("email", "Email Address",
        "required|valid_email");

    if ($this->form_validation->run() == false) {
        $this->load->view("phpmasterform_view");
    }
    else {
        $first = $_POST["first"];
        $last = $_POST["last"];
        $email = $_POST["email"];
        $data = array("first_name" => $first,
                      "last_name" => $last,
                      "email" => $email);

        $this->load->model("phpmasterform_model");
        $this->phpmasterform_model->insert_address($data);
        $this->load->view("formsuccess");
    }
}

What is wrong with this Controller?
The controller doesn’t utilises the full powers of a framework. Any decent framework or a develop methodology will suggest you to move configurations to a separate place. CI has configuration settings for almost everything. The configuration folder is easily identifiable and path is /application/config. In this folder is file autoload.php. This file is commented and is self explanatory. I will move the form helper and form_validation library loading tasks to autoload.php. Read more about it here, Auto-loading Resources. Then in same config folder I will create another file named form_validation.php which will hold all my validation rules. This will be a centralised place to hold all the validation rules. I can easily modify just one file and change validation rules on my whim and fancy. Read more about this here, “Saving Sets of Validation Rules to a Config File“. All these were just small tips and one can read the manual and find more about them. But the biggest mistake I found in this controller was blindly consuming the user input. The commandment of web development says

Thy shalt never trust user input.

CI provides a Input Class library. This library is so important that CI loads it by default. So if you are using CI, use this library.
This was not the only possible security hole. If run through other files in CI, they all start with following line

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

.
This restricts some one from directly accessing the file if path to that file is known.
After all this the controller is changed to following

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
public function index() {
    if (false === $this->form_validation->run(feedback)) {
        $this->load->view("phpmasterform_view");
    }
    else {
/*
    if you have set following "$config['global_xss_filtering'] = TRUE;"in your
    application/config/config.php then you don't need to pass 2nd param as
    true in following three lines.
*/
        $first = $this->input->post("first", true);
        $last = $this->input->post("last", true);
        $email = $this->input->post("email", true);

        $data = array("first_name" => $first,
                      "last_name" => $last,
                      "email" => $email);

        $this->load->model("phpmasterform_model");
        $this->phpmasterform_model->insert_address($data);
        $this->load->view("formsuccess");
    }
}

Following is form_validation.php, this will go in application/config/ folder.

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

$config = array(
    'feedback' => array(
        array(
            'field' => 'first',
            'label' => 'First name',
            'rules' => 'required'
        ),
        array(
            'field' => 'last',
            'label' => 'Last name',
            'rules' => 'required'
        ),
        array(
            'field' => 'email',
            'label' => 'Email',
            'rules' => 'required'
        )
    ),
);

Last thing to do is to modify autload.php and load form helper and form validation library. This should give an idea how to develop a maintainable code in CI.
Happy coding!

Google+ uses Closure Tools

Posted by – November 15, 2011

Google+ like any other Google web application runs fast. It runs on Closure Tools – Google Code. Closure Tools essentially help Google devs to create JavaScript closures, making JS code better and efficient.

Samsung Confirms Ice Cream Sandwich for the Galaxy Note and Galaxy S II

Posted by – November 13, 2011

I have been saving money for Samsung Galaxy SII and then I found that Samsung & Google had planned to come up with some thing better. “Galaxy Nexus“. CRAP!!! Why can’t I just buy a phone and update the OS like any other iPhone owner.  Good news! Samsung Confirms Ice Cream Sandwich for the Galaxy Note and Galaxy S II. I am now going to search for all possible discount coupons in my email or wait for one from e-bay and buy this awesome phone.

Use WordPress Update Services to automatically create static XML feeds

Posted by – August 2, 2011

WordPress blogs server Atom and RSS feeds by default. One can outsource this job to a 3rd party services like feedburner. The existing built-in system in WP serves XML feeds on-the-fly. What that means is a if a feed reader/consumer requests your feed then WP is actually querying MySQL, doing all the back-end server side job and serves a hot, out of the oven, feed every time even if the posts are days or months old. This should not bother a very low traffic blog. But then you can set up WP to create physical static feed files using a plugin. This works for most of the scenarios. But I had a requirement that wanted a remote server to fetch and display those feeds. So even if I had set up a plugin to create static XMLfeeds to avoid server hits, the remote server would still need to query my server introducing network latency. There is a way out. WP has a built in update service that tells remote servers as soon as there is a change in blog. This service is known as “WP update service“. This is a sort of RPC service. You can provide WP a remote URL that should be notified as soon as a change in blog occurs. Now its up to that remote service to take an action on it. On my remote server I set up an action which as soon as receives this update message contacts my blog, fetches a feed and caches it locally. Now the remote server doesn’t need to look at my blog until and unless there is a change, of which it will be notified. One can take this a step further. In update services set up the url to a script on same blog that will connect to your blog and create XML feeds along side your blog files in feedsfolder. Use this code in your in wp-content/themes/{your theme}/functions.php

remove_action( 'wp_head', 'feed_links_extra', 3 ); // Removes the links to the extra feeds such as category feeds
remove_action( 'wp_head', 'feed_links', 2 ); // Removes links to the general feeds: Post and Comment Feed

This will stop printing the default URLs for feed in HTML source and in wp-content/themes/{your theme}/header.php add the URLs for actual feed files that now your script is creating. No need to install a plugin. The only drawback I see here is when you update your skin you loose this particular customisation. Other than that its a pretty good way to create static XML feed files and save your server some hassles.

find & replace in multiple files using egrep & sed

Posted by – July 1, 2011

Programmers are lazy creatures. Any given programmer would love get things done with lesser keystrokes. For instance, find and replace all in multiple files. I was setting up a project on my localhost that some other guy had done. That guy wasn’t a real programmer otherwise what I did would have not been required at first place. The great soul hard-coded all the hyperlinks. What now? I thought of firing an editor and doing a find and replace all by creating a project. Simple. No. I can use grep/egrep to find things then obviously I can chain it to some other command and replace that text. Yes. I am lazy, so instead of experimenting I did some googling. Here is how to do this. Find all files, recursively of course, in current working directory that contain “teh” and replace them with “the”.

egrep -lRZ "teh" ./ | xargs -0 -l sed -i -e 's/teh/the/g'

egrep/grep takes further arguments like type of files to look for, example egrep “teh” *.txt ./ will search for all text files in current working direcotry that contain “teh”. Cool!

So, you can safely say, I can haz teh Linux power!