Tag Archive: codeigniter


File downlaod using CodeIgniter

CodeIgniter has a nice helper class to download files. Its a nice way to download from server without any hassle just writing one single controller function.

public function download ($file_path = "")
	{
			$this->load->helper('download'); //load helper
			
			//$file_path = $this->input->post("file_path",TRUE);
			
			$layout="no_theme"; //if you have layout
			
			$data['download_path'] = $file_path;		
						
			$this->load->view("view file",$data);
			redirect("same url", "refresh");						
					
	}

In view section, just call the download function thats it.

	if( ! empty($download_path))
	{
		$data = file_get_contents(base_url() ."/...path.../".$download_path); // Read the file's contents
		$name = $download_path;

		force_download($name, $data);

	}

Its the most simple process to download using CodeIgniter

Advertisements

The YouTube Data API allows client applications to retrieve and update YouTube content in the form of Google Data API feeds. The client application can use the YouTube Data API to fetch video feeds, comments, responses, and playlists, as well as modify this information and to upload new video content to the site.

There is a awesome Client Library in PHP distributed by Zend is a part of zend framework which is very effective and powerful class to retrieve that from Google. This can be easily integrated with Codeigniter.
Here I share a Class which is very useful to Grad data from Youtube using Gdata class with Codeigniter.

<?php

class Youtube extends Controller
{
	public $layout="default";
	
	function __construct()
	{
		parent::Controller();
		$this->load->library("zend");
		$this->zend->load("Zend/Gdata/YouTube");
		
		$youtube = new Zend_Gdata_YouTube();
		$this->lang->load("resource");
		$this->load->helper("text");
	}

	function index()
	{
	
		//$youtube = new Zend_Gdata_YouTube();
		
		//Grab Video data
		$videoEntry = $youtube->getVideoEntry('video_code');
		
		//Grab Channel data
		$this->getAndPrintUserUploads("youtube_channel_name");
		
		$this->load->view('youtube_view', $data);
	}
	
	function getAndPrintUserUploads($userName)                    
	{     
		  $youtube = new Zend_Gdata_YouTube();
		  $youtube->setMajorProtocolVersion(2);
		  $this->printVideoFeed($youtube->getuserUploads($userName),$page=1,$page_counter=1);
	}  
		
	function printVideoFeed($videoFeed)
	{
		  $data['no_sidebar'] = true;
		  $count = 1;
		  
		  foreach ($videoFeed as $videoEntry) 
		  {
			
				//$this->printVideoEntry($videoEntry);
				$video_info[$count]['title'] = $videoEntry->getVideoTitle();
				$video_info[$count]['id']    = $videoEntry->getVideoId();
				$video_info[$count]['desc']  = $videoEntry->getVideoDescription();
				$video_info[$count]['tags']  = implode(", ", $videoEntry->getVideoTags());
				$video_info[$count]['updated']  = $videoEntry->getUpdated();
				$video_info[$count]['category']  = $videoEntry->getVideoCategory();				
				
				$count++;
		  }
		//pre($video_info);
		
		$data['video_info'] = $video_info;
		$this->load->view("resources/youtube_list_view",$data);
	}
	
		
	
	function printVideoEntry($videoEntry) 
	{
	  // the videoEntry object contains many helper functions
	  // that access the underlying mediaGroup object
	  echo 'Video: ' . $videoEntry->getVideoTitle() . "<br>";
	  echo 'Video ID: ' . $videoEntry->getVideoId() . "<br>";
	  echo 'Updated: ' . $videoEntry->getUpdated() . "<br>";
	  echo 'Description: ' . $videoEntry->getVideoDescription() . "<br>";
	  echo 'Category: ' . $videoEntry->getVideoCategory() . "<br>";
	  echo 'Tags: ' . implode(", ", $videoEntry->getVideoTags()) . "<br>";
	  echo 'Watch page: ' . $videoEntry->getVideoWatchPageUrl() . "<br>";
	  echo 'Flash Player Url: ' . $videoEntry->getFlashPlayerUrl() . "<br>";
	  echo 'Duration: ' . $videoEntry->getVideoDuration() . "<br>";
	  echo 'View count: ' . $videoEntry->getVideoViewCount() . "<br>";
	  echo 'Rating: ' . $videoEntry->getVideoRatingInfo() . "<br>";
	  echo 'Geo Location: ' . $videoEntry->getVideoGeoLocation() . "<br>";
	  echo 'Recorded on: ' . $videoEntry->getVideoRecorded() . "<br>";
	  
	  // see the paragraph above this function for more information on the 
	  // 'mediaGroup' object. in the following code, we use the mediaGroup
	  // object directly to retrieve its 'Mobile RSTP link' child
	  foreach ($videoEntry->mediaGroup->content as $content) {
		if ($content->type === "video/3gpp") {
		  echo 'Mobile RTSP link: ' . $content->url . "<br>";
		}
	  }
  
  echo "Thumbnails:<br>";
  $videoThumbnails = $videoEntry->getVideoThumbnails();

		  foreach($videoThumbnails as $videoThumbnail) {
			echo $videoThumbnail['time'] . ' - ' . $videoThumbnail['url'];
			echo ' height=' . $videoThumbnail['height'];
			echo ' width=' . $videoThumbnail['width'] . "<br>";
		  }
	}

}

?>

Zend provides some cool library classes for Youtube.

There is another way to grab youtube data from youtube Channel that is grabbing from API feed. Which is another easy process.


/**
 * Function: youtube data grabber
 *
 * @description :
 * @param  $ : video code, url type (embed/url)
 * @return : data array
 * @author : Mamun.
 * @last -modified-by: Mamun.
 */
if (! function_exists('youtube_data_grabber' ))
{

		function youtube_data_grabber($video_code, $link_type = "embed")
		{
				if ($video_code != '')
				{
					if ($link_type == "embed")
					{
						$splited_data = explode("=",$video_code);
						$video_unique_code = substr(strrchr($splited_data[4],"/"),1,-strlen(strrchr($splited_data[4],"&")));

					}
					else if ($link_type == "url")
					{
						$splited_data = explode("=",$video_code);
						$video_unique_code = substr($splited_data[1],0,-strlen(strrchr($splited_data[1],"&")));
					}
					else
					{
						return;
					}

						// set feed URL
						$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$video_unique_code;

						// read feed into SimpleXML object
						$sxml = simplexml_load_file($feedURL);

					return $sxml;
				}

		}
}

JQ Grid with Codeigniter

jQGrid is a free jQuery grid and table plugin. I had awesome working experience on JQGrid. Its is very simple and easy to integrate with the main library. last couple of days, I received some requests on how to integrate JQGrid with Codeigniter.

Follow the steps to integrate JQGrid with CI:

Controller:

public function browse ()
	{
		$req_param = array (

				"sort_by" => $this->input->post( "sidx", TRUE ),
				"sort_direction" => $this->input->post( "sord", TRUE ),
				"page" => $this->input->post( "page", TRUE ),
				"num_rows" => $this->input->post( "rows", TRUE ),
				"search" => $this->input->post( "_search", TRUE ),
				"search_field" => $this->input->post( "searchField", TRUE ),
				"search_operator" => $this->input->post( "searchOper", TRUE ),
				"search_str" => $this->input->post( "searchString", TRUE ),
				"search_field_1" => "msg_to",
				"search_field_2" => "msg_in_inbox",
				"user_id" => get_user_id()
		);

		$data->page = $this->input->post( "page", TRUE );
		$data->records = count ($this->model_name->get_data ($req_param,"all")->result_array());
		$data->total = ceil ($data->records /10 );
		$records = $this-> model_name-> get_data ($req_param)->result_array();
		$data->rows = $records;

		echo json_encode ($data );
		exit( 0 );
	}

Models:

public function get_data($params = "" , $page = "all")
	{

		$this->db->select("data")->from( "table_name");

		if (!empty($params))
		{
			if ( (($params ["num_rows"] * $params ["page"]) >= 0 && $params ["num_rows"] > 0))
			{
				if  ($params ["search"] === TRUE)
				{
					$ops = array (

							"eq" => "=",
							"ne" => "<>",
							"lt" => "<",
							"le" => "<=",
							"gt" => ">",
							"ge" => ">="
					);

				}

				if ( !empty ($params['search_field_1']))
				{
					$this->db->where ($params['search_field_1'], $params['user_id']);
				}

				if ( !empty ($params['search_field_2']))
				{
					$this->db->where ($params['search_field_2'], "1");
				}

				$this->db->order_by( "{$params['sort_by']}", $params ["sort_direction"] );

				if ($page != "all")
				{
					$this->db->limit ($params ["num_rows"], $params ["num_rows"] *  ($params ["page"] - 1) );
				}

				$query = $this->db->get();

			}
		}
		else
		{
				$this->db->limit (5);
				$query = $this->db->get ($this->_table );

		}
		return $query;
	}

Views:

<script type="text/javascript">
$(document).ready(function(){
	jQuery("#grid_name").jqGrid({
	   	url:'<?php
		      echo site_url( "message/inbox/browse" );
		      ?>',
		datatype: "json",
		mtype : "post",
		colNames:['col 1','col 2','col 3','col 4'],
	   	colModel:[
			{name:'msg_id',index:'msg_id', width:70, align:"center",hidden:true},
	   		{name:'sender',index:'sender', width:180},
	   		{name:'msg_subject',index:'msg_subject', width:180,align:"left"},
	   		{name:'msg_timestamp', index:'msg_timestamp', width:150},
	   		{name:'act',index:'act', width:90, align:"center", sortable:false}
	   	],
	   	rownumbers: true,
	   	rowNum:10,
	   	rowList:[10,20,30],
	   	pager: jQuery('#pager2'),
	   	sortname: 'msg_timestamp',
	   	autowidth: true,
	   	height: "100%",
	    viewrecords: true,
	    loadComplete: function(){
						$("#grid_name").setLabel("id","",{'text-align':'center'});
						$("#grid_name").setLabel('role_name',"",{'text-align':'center'});
						var ids = jQuery("#grid_name").getDataIDs();
							for(var i=0;i<ids.length;i++){

								var cl = ids[i];

								be = '<span class="one_line">'
								+'<a href="javascript:;" onclick="del_message(\''+ids[i]+'\');"><span class="ui-icon ui-icon-closethick"></span></a>'
								+'</span>';
								jQuery("#grid_name").setRowData(ids[i],{act:be});
							}
					    },

	    sortorder: "desc",

	    jsonReader: { repeatitems : false, id: "0" },
	    caption:"Caption Text");?>"
	}).navGrid('#pager2',{edit:false,add:false,del:false});
});

function del_message(message_id)
{
	if(confirm("Confirm Message")){

		$.ajax({
			url : site_url+"/message/inbox/del_message",
			type : "post",
			dataType : "json",
			data : "message_id="+message_id+"",
			success : function(e){
				$("#msg").html(e.msg)
				alert($("#msg").html());
				//$.jGrowl(e.code+"<br>"+e.message);
				jQuery("#grid_name").trigger("reloadGrid");
			}
		});
	}
}

</script>

HTML BODY:

<table id="grid_name" cellpadding="0" cellspacing="0"></table>
<div id="pager2" class="scroll" style="text-align: center;"></div>

Hope this looks very easy to integrate with CI. Enjoy 🙂

Internationalization (i18n) Library is an extension of  CodeIgniter Language Library. Recently I extended this library with codeIgniter main language to build a multi-language site and found that very easy and interesting to implement codeigniter HMVC structure.

How It works:

It places the language in the URL

  • yoursite.com/en/about
  • yoursite.com/fr/about

Need an extension with  CodeIgniter Language Class

View:

<p>
  <?=lang('about.gender')?>
</p>

English language file:
$lang['about.gender'] = "I'm a man";

French language file:
$lang['about.gender'] = "Je suis un homme";

Installation:

  • Download: here
  • Put MY_Language.php and MY_Config.php in system/application/libraries

Configuration :

  • You must be using pretty URLs (without index.php). With Apache it’s usually achieved with mod_rewrite through an .htacess

In config.php

  • $config[‘base_url’] must correspond to your configuration.
  • $config[‘index_page’] = ””

In config/routes.php add

<?php
// URI like '/en/about' -> use controller 'about'
$route['^fr/(.+)$'] = "$1";
$route['^en/(.+)$'] = "$1";
 
// '/en' and '/fr' URIs -> use default controller
$route['^fr$'] = $route['default_controller'];
$route['^en$'] = $route['default_controller'];
?>

Use:

You have to build a bilingual English/French page.

language files:

system/application/language/english/about_lang.php

<?php
 
$lang['about.gender'] = "I'm a man";
 
/* End of file about_lang.php */
/* Location: ./system/language/english/about_lang.php */

system/application/language/french/about_lang.php
<?php
 
$lang['about.gender'] = "Je suis un homme";
 
/* End of file about_lang.php */
/* Location: ./system/language/french/about_lang.php */

Controller:

 
system/application/controllers/about.php

<?php
class About extends Controller {
 
    function index()
    {
        // you might want to just autoload these two helpers
        $this->load->helper('language');
        $this->load->helper('url');
 
        // load language file
        $this->lang->load('about');
 
 
        $this->load->view('about');
    }
}
 
/* End of file about.php */
/* Location: ./system/application/controllers/about.php */

View:


 system/application/views/about.php
 

<p><?=lang('about.gender')?></p>

<p><?=anchor('music','Shania Twain')?></p>

For more click here

Whats new in CodeIgniter?

CodeIgniter new version 1.7.2 has been released with more compitable features with PHP 5.x.x.

EllisLab is pleased to release CodeIgniter version 1.7.2 which is ready for download. What’s new in CodeIgniter ?

The following feature has been added in new release:

  • Compatible with PHP 5.3.0
  • Added a new Cart Class.
  • Improvements to the Form helper
  • Added is_php() to Common functions to facilitate PHP version comparisons
  • Modified show_error() to allow sending of HTTP server response codes,and all internal uses now send proper status codes.
  • Numerous bug fixes

Version 1.7.2 has been baking in the subversion for quite some time, and has been compatible with PHP 5.3.0 since late July

CodeIgniter is improving very faster and getting rich day by day.