File Upload and Validation in CodeIgniter

In this article, we are going to discuss about How to do the file upload and validation in CodeIgniter. I would like to explain how to upload files to server in CodeIgniter and to validate it with Form Validation library.

  1. How to upload files to server
  2. How to Validate file before uploading
  3. How to upload files to server

Step 1 :

Create a view that contains form fields and a field with input type file (Register.php) and add the below code in that file.

<?php echo form_open_multipart('welcome/register/'); ?>

form_open_multipart is used to upload files. It supports the input type file. Next we have to add other form fields and fiel field.

<?php echo validation_errors('<p class="form_error">','</p>'); ?>
<?php echo form_open_multipart('welcome/register/'); ?>
<input type="text" name="firstname" placeholder="Enter your Firstname"/>
<input type="text" name="city" placeholder="Enter your City"/>
<input type="file" name="userimage">
<button type="submit">Create Account</button>
</form>

Step 2:

Now, the form is submitted to the Register method in Welcome controller. Our Register method in Welcome contoller looks like this Welcome.php

public function register(){
     $this->load->library('form_validation');
     $this->form_validation->set_rules('firstname', 'First Name', 'required|trim|xss_clean');
     $this->form_validation->set_rules('city', 'City', 'required|trim|xss_clean');
     $this->form_validation->set_rules('userimage', 'Profile Image', 'callback_image_upload');
     if($this->form_validation->run() == TRUE){
         echo "Account Created Successfully";
     }
     $this->load->view('register');
}

Step 3:

Create a callback function for uploading image and validation. Method image_upload looks like the following.

function image_upload(){
      if($_FILES['userimage']['size'] != 0){
        $upload_dir = './images/';
        if (!is_dir($upload_dir)) {
             mkdir($upload_dir);
        }  
        $config['upload_path']   = $upload_dir;
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['file_name']     = 'userimage_'.substr(md5(rand()),0,7);
        $config['overwrite']     = false;
        $config['max_size']  = '5120';
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('userimage')){
            $this->form_validation->set_message('image_upload', $this->upload->display_errors());
            return false;
        }  
        else{
            $this->upload_data['file'] =  $this->upload->data();
            return true;
        }  
    }  
    else{
        $this->form_validation->set_message('image_upload', "No file selected");
        return false;
    }
}

Explaining the callback function.

Steps Involved are

  • First we are checking if the file is submitted with the form. If the file is empty, we are setting the form validation error message as "No file selected".
  • We are creating a directory if the directory does not exist.
  • We have to configure the directory path, allowed upload files, filename, maximum file size, maximum width, maximum height etc.,
  • Then we are uploading the file. If upload fails, error message is set to the form validation.


Hope this is helpful.

Yii – Load modules dynamically from db or directory

In this article, we are going to discuss about How to load the modules dynamically from DB or from Directory in YII framework. In Yii application development, we can set up modules configuration in config.php.  Sometimes, we need to load modules configuration from database or directory glob. After searching the topic in google and comparing some solutions, I found the elegant way to implement this. Hope it can help.

You can modify the index.php file of your Yii application.

require_once($yii);

class ExtendableWebApp extends CWebApplication {
        protected function init() {
                // this example dynamically loads every module which can be found
                // under `modules` directory
                // this can be easily done to load modules
                // based on MySQL db or any other as well
                foreach (glob(dirname(__FILE__).'/protected/modules/*', GLOB_ONLYDIR) as $moduleDirectory) {
                        $this->setModules(array(basename($moduleDirectory)));
                }
                return parent::init();
        }
}

$app=new ExtendableWebApp($config);
$app->run();

Reference: http://www.yiiframework.com/forum/index.php/topic/23467-dynamically-load-modules-models-and-configurations/page__p__144316#entry144316

Magento Functional and Factory class groups

In this article, we are going to discuss about the Functional and Factory class groups in Magento. As you know Magento is built based on module architecture, which leads to the requirement that there must be an interaction between modules. Hence, in this part we will learn about the way these modules used.

Definition and Examples of Functional and Factory class groups

Functional Class
  •     Class: only contains functions and static attributes? (not sure)
  •     For example: Mage

Factory Class

  •     Class: consists of functions to create the instance (object) of different Classes. Class depends on input parameters
  •     For example: class Mage

Create an instance of class Mage_Catalog_Model_Product

Mage::getModel('catalog/product')

Generate an instance of class Mage_Catalog_Block_Product_View

Mage::getBlockSingleton('catalog/product_view')

Definition of Instance, the ways to create the instance object in Magento

  • Definition : In OOP, Instance is an Object
  • Create an instance object in Magento

Mage::getModel('catalog/product');
Mage::getBlockSingleton('catalog/product_view');
Mage::app()->getLayout()-createBlock('catalog/product_view')

The process to generate an instance through the function Mage::getModel() is as below:

1) Call function getModel() trong class Mage

2) Call function getModelInstance() in class Mage_Core_Model_Config

3) Call function getModelClassName(). This function will return the name of the model with catalog/product is Mage_Catalog_Model_Product.

4) Add a new object by the New command:

$obj = new $className($constructArguments);

In this example, $className = 'Mage_Catalog_Model_Product'

Get different instances from different places:

– With creating a Instance of a model, the function Mage::getModel() always returns a new object (instance).

– Function Mage::getSingleton() always gives only one object (instance) back.

Download and install Drupal modules using Drush

In this article, we are going to discuss about How to download and install Drupal modules using Drush command. One of the best things about building websites with Drupal is that there are thousands of modules that help you quickly create functionality.

To set things up, you need to download Drush and add it to your path. For example, you might unpack it into /opt/drush and then add the following line to your ~/.bashrc:

PATH=/opt/drush:$PATH
export PATH

Reload your ~/.bashrc with source ~/.bashrc, and the drush command should become available. If you're on Microsoft Windows, it might need some more finagling. (Or you can just give up and use a virtual image of Linux to develop your Drupal websites.

Drush is a huge time-saver. For example, I install dozens of modules in the course of building a Drupal website. Instead of copying the download link, changing to my sites/all/modules directory, pasting the download URL into my terminal window after wget, unpacking the file, deleting the archive, and then clicking through the various module enablement screens, I can just issue the following commands to download and enable the module.

drush dl modulename
drush en -y modulename
(The -y option means say yes to all the prompts.)

So much faster and easier. You can use these commands with several modules (module1 module2 module3), and you can use drush cli to start a shell that's optimized for Drush.

Drush is also useful if you've screwed up your Drupal installation and you need to disable themes or modules before things can work again. In the past, I'd go into the {system} table and carefully set the status of the offending row to 0. Now, that's just a drush dis modulename.

Drush has a bucketload of other useful commands, and drush help is well worth browsing. Give it a try!