Monday 24 September 2012

Uploading multiple files in codeigniter

In this page Iam describing about uploading multiple images in codeigniter:-



public function uploadfiles(){
$this->load->helper('form');
$this->load->helper('url');
$data['urls']=base_url();
$this->load->view('templates/headermain',$data);
$this->load->view('admin/uploadfiles',$data);
$this->load->view('templates/footermain',$data);
$save=$this->input->post('saveForm');
if($save){
$error=0;
 $this->load->library('upload');  // NOTE: always load the library outside the loop

 /*Because here we are adding the "$_FILES['userfile']['name']" which increases the count, and for next loop it raises an exception, And also If we have different types of fileuploads */
 for($i=0;$i<count($_FILES);$i++)///loop through count
 {

   $_FILES['userfile']['name']    = $_FILES['filename'.$i]['name'];
   $_FILES['userfile']['type']    = $_FILES['filename'.$i]['type'];
   $_FILES['userfile']['tmp_name'] = $_FILES['filename'.$i]['tmp_name'];
   $_FILES['userfile']['error']       = $_FILES['filename'.$i]['error'];
   $_FILES['userfile']['size']    = $_FILES['filename'.$i]['size'];

   $config['file_name']     = 'test_'.$i;
   $config['upload_path'] = 'uploads/'; 
   $config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = '1000'; 
$config['max_width'] = '1920'; 
$config['max_height'] = '1280';
   $config['overwrite']     = FALSE;

  $this->upload->initialize($config);

  if($this->upload->do_upload())
  {
    $error += 0;
  }else{
    $error += 1;
  }
 }

 if($error > 0){ echo "error"; }else{ echo "success"; }
}
}


Uploading image and generating thumbnail in Codeigniter

In this page Iam explaining how to upload image using codeigniter.
Before doing the code make sure that you created afolder named uploads in the rootfolder. and also a folder named thumbs inside this uploads folder.
So in the file uploading html page code should be like this:-

<?php echo form_open_multipart('admin/imageadd'); ?>
 <div class="row">
                            <div class="row150">
                                <h6>Image
                                <span class="req">*</span></h6>
                            </div>
                            <div class="row350">
                                <input type="file" name="userfile"  size="40" maxlength="90" tabindex="3" class="browse"/>
                            
                            </div>
                        </div>

<input name="saveForm" type="submit" value="." class="iconSave" />

                        
In the controller page code should be like this:-

public function imageadd(){
$save=$this->input->post('saveForm');
if($save){
$config['upload_path'] = 'uploads/'; 
$config['allowed_types'] = 'gif|jpg|jpeg|png'; 
$config['max_size'] = '1000'; 
$config['max_width'] = '1920'; 
$config['max_height'] = '1280';

$this->load->library('upload', $config); 
if(!$this->upload->do_upload()) 
$this->upload->display_errors(); 
else { 
$fInfo = $this->upload->data(); //uploading
  $this->gallery_path = realpath(APPPATH . '../uploads');//fetching path

$config1 = array(
      'source_image' => $fInfo['full_path'], //get original image
      'new_image' => $this->gallery_path.'/thumbs', //save as new image //need to create thumbs first
      'maintain_ratio' => true,
      'width' => 150,
      'height' => 100
       
    );
    $this->load->library('image_lib', $config1); //load library
    $this->image_lib->resize(); //generating thumb
}

$imagename=$fInfo['file_name'];// we will get image name here
}

After this if u look at the uploads folder you can see the image file there and its thubnail image inside the thumb folder...

Updating and deleting data in codeigniter

In this page iam describing about updating data in a codeigniter. Here iam explaining with the help of an example, so that you can understand it easily:-

UPDATING DATA

Usually there araise situation whereyou want to update the content added.
Generally we have to pass id of record from a record listing to a page to edit a particular record. In codeigniter we can do with built in function like this :-
 <?php echo anchor('admin/updatenews/' .$news_item['news_id'],"Update", array('title' => $ads_id = $news_item['news_id']));?>

so here id will be passed through the url:-
url wll be looking something like this:-
http://localhost/CodeIgniter/index.php/admin/updatenews/24

In codeigniter you can retrieve data like this:-
$newsid = $this->uri->segment(3);

you will get $newsid like this.


public function updatenews(){

$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$this->form_validation->set_rules('txtTitle', 'title', 'required');
$this->form_validation->set_rules('txtContent', 'content', 'required');
$data['urls']=base_url();
 $newsid = $this->uri->segment(3);
$news=$this->news_model->getnewsitem($newsid);//retreiving newsitem
$data['news']=$news;

$this->load->view('templates/headermain',$data);
$this->load->view('admin/updatenews',$data);
$this->load->view('templates/footermain',$data);
$save=$this->input->post('saveForm');
if($save){

$list=array('title'=>$title,'content'=>$content,'publish'=>$publish,'id'=>$newsid);//
$this->news_model->updatenews($list);//pasing as array to the model
redirect('admin/news',$data); 
}

so you have to write afunction in model like this :-


public function updatenews($list)

$dateup=date('Y-m-d H:i:s');
$data = array(
'published'=>$list['publish'],
'title' =>$list['title'],
'content' => $list['content'],
'date_update'=>$dateup
);

$this->db->where('news_id',$list['id']);
                   $this->db->update('news',$data); 
                   return 1;
}

and your update html view would be like:-

  <?php

$attributes=array('newsid'=>$news[0]['news_id']);
                      echo form_open_multipart('admin/updatenews',$attributes); ?>// here attributes can be passed like this




<h6>Title
                             </h6>
                          
                            <div class="row450">
                       Title:-      <input type="text" name="txtTitle"  size="40" maxlength="90" tabindex="2" value="<?php echo $news[0]['title']; ?>"  class="txtAdd_new">
                            </div>
content:-
<textarea name="txtContent" id="txtContent" rows="10" cols="40" tabindex="6"><?php echo $news[0]['content']; ?></textarea>


DELETING DATA

For deleting data you can use this function :-

 $this->db->where('news_id',$list[$i]);
                   $this->db->delete('news',$data); 





Listing data in codeigniter

In this page  , Iam describing about doing basic functions in codeigniter like listing data, inserting data, deleting data, updating data,uploading images,generating thumbnail of images.etc. If you are doing a simple project website in codeigniter this page will be useful for you.

Listing data
............................

Here iam describing an example of a news adding website. so in that project we will certainly have a page where all data will be listed. For details about where to add controller,model and view refer my previous page:- http://phpdudes.blogspot.in/2012/09/codeigniter-sample-project.html

First you have to write method in controller:-

public function news(){
$this->load->helper('form');
$this->load->helper('url');
$data['urls']=base_url();//basic root url
$data['news'] = $this->news_model->get_news();// retreive newslist from model
$data['count']=count($data['news']);
$this->load->view('templates/headermain',$data);//loading the header
$this->load->view('admin/news',$data);
$this->load->view('templates/footermain');//loading the footer

}
So you have a function named get_news in the news model:-


public function get_news()
{

$query = $this->db->get('news');
return $query->result_array();

}

So in the view page you have to code like this:-

  foreach($news as $news_item){
                   
                        ?>
                        <li>
                           <input type="hidden" name="id<?php echo $i;?>" value="<?php echo $news_item['news_id'];?>" />
            <div class="row250"><?php echo $news_item["title"];?></div>
<?php } ?>

Friday 21 September 2012

CodeIgniter- A sample project

CodeIgniter is a toolkit for people who build web applications using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task. codeigniter is similar o cakephp which is another framework of php.

INSTALLATION
           
You can download codeigniter latest vesion from their site http://codeigniter.com/downloads/
after download you copy it to the wamp->www folder.

  • At first step, you have to configure database for the project.
  • You can configure database at pplications/config folder.

CONFIGURATION
       Just like most MVC frameworks, codeigniter also have model,view ,controller folders You can create corresponding models,views and controllers inside each  folder.

Here iam explaining to create a sample project in codeigniter.

SAMPLE PROJECT

In this project iam creating a news listing website.

create a database named news and create a table named news 


CREATE TABLE news (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(128) NOT NULL,
text text NOT NULL,
PRIMARY KEY (id),
KEY slug (slug)
);
change the default controller in routes.php like this

$route['default_controller'] = 'news/index';
$route['(:any)'] = 'news/index/$1';



First create a controller named news and save it as news.php inside controller folder.

<?php

class News extends CI_Controller {



public function __construct()// constuctor
{
parent::__construct();
$this->load->model('news_model');// load news_model at startup
}

public function index($page = 'index')
{
$data['news'] = $this->news_model->get_news();// function writen in model
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer', $data);

}

}
?>
Here we are loading three view files ,so we have to create them.

1) create a header.php named file and save it inside view folder in a folder named templates and paste folllowing code into it:-
<html>
<head>
<title>News listing</title>
</head>
<body>
<h1> News</h1>

2) create a footer.php named file and save it inside the view folder ina folder named templates and pate the following code into it:-
<strong>&copy; 2012</strong>
</body>
</html>

Thus we are successful in creating a layout for our files.

3) Next we have to create view file for news index. for this create a folder named news inside view folder. and then create a php file named index.php.

But before that we want to prepare a model for news,so that we can fetch data from the database.

create a model named news_model.php and save in the folder model.

<?php
class News_model extends CI_Model {

public function __construct()
{
$this->load->database();// loading the databse
}

public function get_news($title = FALSE)
{
if ($title === FALSE)
{
$query = $this->db->get('news');//getting all news
return $query->result_array();// returing array of data
}
$query = $this->db->get_where('news', array('title' => $title));// getting news with conditions
return $query->row_array();// returing array of data
}

}
?>

so now it's time to create index view for news.

<?php foreach ($news as $news_item): ?>

    <h2><?php echo $news_item['title'] ?></h2>
    <div id="main">
        <?php echo $news_item['text'] ?>
    </div>
    

<?php endforeach ?>

Here news will be fetched one byone...

For adding data to database
...................................................

Here iam explaining how to add data to databse using codeigniter.

first create html view as create.php in folder news inside view folder

<h2>Create a news item</h2>

<?php echo validation_errors(); ?>

<?php echo form_open('news/create') ?>

<label for="title">Title</label> 
<input type="input" name="title" /><br />

<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" /> 

</form>




create a function in contoller named create

public function create()
{
$this->load->helper('form');// helper library default of codeigniter
$this->load->library('form_validation');// helper library default of codeigniter
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');// we have to set criteria of each form elemen, it will evaluate automaticallly
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE)// if valiadtion false then return error message
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');// success message will be shown
}
}

Now  it's time to create model function

public function set_news()
{
$this->load->helper('url');

$data = array(
'title' => $this->input->post('title'),
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);// data will be inserted to database
}

Download from here:- https://github.com/litto/Codeigniter3-Sample-Project-with-CRUD

Tuesday 18 September 2012

htaccess writing for websites


A .htaccess (hypertext access) file is a directory-level configuration file supported by several web servers, that allows for decentralized management of web server configuration.
The original purpose of .htaccess - reflected in its name - was to allow per-directory access control, by for example requiring a password to access the content. Nowadays however, the .htaccess files can override many other configuration settings including content type and character set, CGI handlers, etc.
These files are placed inside the web tree, and are able to override a subset of the server's global configuration for that directory, and all sub-directories.
With the help of htaccess we can even block users from different ip's.
Iam here describing some of the basic htaccess examples :-


1)Redirecting index.html to index.php

RewriteEngine On
RewriteRule index.html  index.php

Here index.html in url is redirected to index.php

2)Redirecting services-servicename-8.html to services.php?id=8

RewriteEngine On
RewriteRule services-([a-zA-Z0-9\-]+)-([0-9]+).html services.php?id=$2 [NC]

3)Redirecting services-8-servicename.html to services.php?id=8


RewriteEngine On
RewriteRule services-([0-9]+)-([a-zA-Z0-9\-]+).html services.php?id=$1 [NC]

Look at the examples of 2 and 3

In the 2nd rule is explained like :- if a url comes like services-any keywordname-number.html,then it shoul redirect to sevices.php?id=number in the second partition, because id is provided their.

In the 3rd rule is explained like :- if a url comes like services-idnumber-sevicename.html then it shoul redirect to services.pho?id=number in the first partition, because id is provided there.


if url is like  services-([a-zA-Z0-9\-]+)-([a-zA-Z0-9\-]+)-([0-9]+).html 

then redirecting url shoul be like services.php?id=$3 [NC]

$3-> because id is provided in the third partition

4) Redirecting a folder to another folder

RewriteEngine on
RewriteRule ^(.*)/category-old/(.*)$ $1/category-new/$2 [R,L] 
Here request for folder named category-old should redirect o category-new folder


Extracting Zip in purephp

When we are doing dynamic sites, their araise situation where we want to extract zipped files. so iam explaining here one way to extract zip files using corephp.
 for doing this first you have to ensure that your server has zip extension enabled. then if it is enabled simply follow the steps which iam explaining:-

1) First you have to include a zip library. here iam using pclzip library.
just download file from http://www.phpconcept.net/pclzip/pclzip-downloads



2)Now you have to include it in your zip uploading page like :-
include("pclzip.lib.php");

3) Uploading html code is similar to the image uploading itself
 <form action="theme-create.php" method="post" enctype="multipart/form-data">
 <div class="row">
                            <div class="row150">
                                <h6>Upload zip:
                                <span class="req">*</span></h6>
                            </div>
                            <div class="row350">
                                <input type="file" name="txtFile1"  size="40" maxlength="90" tabindex="3" class="browse"/>
                            
                            </div>
                        </div>
</form>

4) create a class named Uploader and copy below code to it 
<?php
/*
 * Date:8-16-2012
 * Login Form , entry to the application
 * Auhthor : Litto chacko
 * Email:littochackomp@gmail.com
*/
    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
private $seqnence;
        
        function __construct($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }
        
        function allowAllFormats(){
            $this->allowAll =   true;
        }
        
        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }
        
        function setExtensions($options){
            $this->extensions   =   $options;
        }
        
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
        function getExtension($string){
            $ext = "";
            try{
                    $parts = explode(".",$string);
                    $ext = strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext = "";
            }
            return $ext;
}
        
        function setMessage($message){
            $this->errorMessage =   $message;
        }
        
        function getMessage(){
            return $this->errorMessage;
        }
        
        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
$this->imageSeq = $seq;
}
function sameName($true){
$this->sameName = $true;
}
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
                $util   =   new Utilities();
if($this->sameName==false){
                $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$util->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
$this->uploadName= $name;
}
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }
        
        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }
        
    }

?>


5) So in the action side you have to do code like this... create afolder named themes in the same folder.. so that extracted files will be extracted to this folder

          $uploader   =   new Uploader($absDirName.'/');//object of uploader
            $uploader->setExtensions(array('zip'));
            $uploader->setSequence('theme');
            $uploader->setMaxSize(10);
            if($uploader->uploadFile("txtFile1")){
        
                 $image1     =   $uploader->getUploadName(); 
                
            } 
    

$file_to_open=$absDirName.'/'.$image1;
$zip = new PclZip($file_to_open);// creating object of pclzip
$target="/themes/";
$unique_folder="theme";
chmod($target.'/'.$txtTitle,0777);//changing permission of folder to writable
if ($zip->extract(PCLZIP_OPT_PATH, $target) == 0) {//extracting zip files
   $message    =   new Message('problem in extracting files','error');
            $message->setMessage();
              header('Location:themes.php');
            exit;
6) Now zip file will be extracted