Category: Code Igniter


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;
				}

		}
}

You Tube provides two types (small/large) of thumbnails for each video. It quite simple task to grab thumbnail from YouTube video. I created this function for grabbing thumbnails form YouTube videos. Its able to grab from both URL and Embedded code and also small and large size.

Function Body:

/**
* Function: youtube thumb grabber
*
* @description :
* @param  $ : video code, url type (embed/url),size (small/Large),thumb link
* @return : thumb path
* @author : Mamun.
* @last -modified-by: Mamun.
*/
if (! function_exists('youtube_thumb_grabber' ))
{

     function youtube_thumb_grabber($video_code, $link_type = "embed", $size = "small", $thumb_link = "")
    {
            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;
                  }

                  if($size == "small")
                  {
                            return "<a href=\"$thumb_link\"><img src=\"http://img.youtube.com/vi/$video_unique_code/2.jpg\" alt=\"No image\" /></a>";
                  }
                  else if ($size == "large")
                  {
                            return "<a href=\"$thumb_link\"><img src=\"http://img.youtube.com/vi/$video_unique_code/0.jpg\" alt=\"No image\" /></a>";
                  }
                  else
                  {
                            return "<a href=\"$thumb_link\"><img src=\"http://img.youtube.com/vi/$video_unique_code/2.jpg\" alt=\"No image\" /></a>";

                   }

             }

      }
}

Calling Function:

<?php 

echo youtube_thumb_grabber($video["video_code"],"embed","small","resources/videos/view/".$video["video_title_url"]);

?>

Its Cool. ūüėÄ

In all Entertainment sites, Star rating is a common phenomena. We need to use star rating for rating different resources like videos, articles, thesis, posts even sometimes persons. JQuery has an excellent Star Rating plugin, which I recently use with PHP CodeIgniter. This is very simple to integrate with controller and show high quality rating options.

Jquery Call:


$(function() {
       $('.auto-submit-star').rating({
            required: true,
            callback: function(value, link) {

            $.ajax({
                     type: "post",
                     url: site_url + "user/view/star",
                     dataType: "json",
                     data: "&video=" + $('#video_url').val() + "&rate_val=" + value,

              success: function(e) {
                   $.jGrowl(e.code + "<br>" + e.msg);
               }
         });
     }
});

Controller Method:

public function star()
    {
        $rate = $this->input->post("rate_val", true);
        $video_url = $this->input->post("video", true);
        $this->load->model("Model Name");
        $video_id = $this->model_name->get_video_id($video_url);
        unset($this->layout); //Block template Layout
        if (get_user_id())   //get_user_id() return login user id
        {
            if (!$this->model_name->is_video_rated(get_user_id(), $video_id))
            {
                $data = array("video_id" => $video_id,
                    "user_id" => get_user_id(),
                    "videos_rating_value" => $rate,
                    "videos_rating_date" => "" . date("Y-m-d H:i:s") . ""
                    );
                if ($this->model_name->insert_rating($data, $video_id, $rate))
                {
                    echo json_encode(array("code" => "Success", "msg" => "Your Video Rating has been posted"));
                }
                else
                {
                    echo json_encode(array("code" => "Error", "msg" => "There was a problem rating your video"));
                }
            }
            else
            {
                echo json_encode(array("code" => "Error", "msg" => "You have already rated this video"));
            }
        }
        else
        {
            echo json_encode(array("code" => "Error", "msg" => "You have to login to rate the video"));
        }
        exit(0);
    }

Presentation View:

    if (!get_user_id()) //Check if user logged in
    {
        $radio_level = "disabled";
    }
    else
    {
        $radio_level = " ";
    }

    for($i = 1;$i <= 5;$i++)
    {
        if ($i == round($row["total_rate"]))
        {
       ?>
       <input class="auto-submit-star" type="radio" name="rating" <?php echo "$radio_level";

            ?> value="<?php echo $i;

            ?>" checked="checked"/>
	<?php
        }
        else
        {
         ?>
	<input class="auto-submit-star" type="radio" name="rating" <?php echo "$radio_level";

            ?> value="<?php echo $i;

            ?>"/>
   <?php
        }
    } //end of for
?>
    

Its a very cool ūüôā rating JQuery plugins.
For demo click

Add This feature helps website publishers and bloggers spread their content across the web by making it easy for visitors to bookmark and share content to their favorite social destinations. Here I share my recently developed widget for Add This Service which can be easily integrate with PHP application.


/**
 * Function: share_addthis
 *
 * @description : share with Add This bookmarking service
 * @param  $ : $val
 * @return : String
 * @author : Mamun
 */
 function share_addthis($brand = "", $link_title = "Share" , $opt_array = "")
 {

 if(!empty($opt_array))
 {
 $opt = $opt_array;
 }
 else
 {
 $opt = array("digg", "facebook", "favorites", "furl", "google","linkedin", "live","multiply", "myspace",  "reddit", "segnalo", "haredstuff",  "stumbleupon", "technorati", "twitter");
 }

 $share_options = "";

 foreach ($opt as $option)
 {
 $share_options .= $option.", ";
 }

 $share_options = $share_options." more";

 $share_element= '<script type="text/javascript">
 var addthis_pub="'.$brand.'";
 var addthis_brand = "'.$brand.'";
 var addthis_header_color = "#ffffff";
 var addthis_header_background = "#1783C6";
 var addthis_options = "'.$share_options.'";
 </script>';

 $share_element.= '<script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script>';

 $share_element .= "<a href=\"http://www.addthis.com/bookmark.php?v=20\" target=\"_blank\" onmouseover=\"return addthis_open(this, '', '[URL]', '[TITLE]')\" onmouseout=\"addthis_close()\" onclick=\"return addthis_sendto()\">$link_title</a>";

 return $share_element;

 } // End Function share_addthis()

Call this widget with your project name, share Label and share options and it will automatically display the Add this icons.


share_addthis($brand = "Your Project Name", $link_title = "Share" , $opt_array = "")

Last week, I was distaste with a problem with string validation in Codeigniter.¬† I used alpha_dash function from Validation class to validate string for alpha numeric character and Dash. Alpha Dash have a problem, It support alphanumeric characters with dash but unfortunately it doesn’t support Space. That’s really a problem.

At last, I had no other way except customize that library function and I built my own helper function using space support on its regular expression pattern.

<?php
function alpha_dash($str)
    {
        return ( ! preg_match("/^([-a-z0-9_-\s])+$/i", $str))
                         ? FALSE : TRUE;
    }
?>

I just added “\s” with the main Regular Expression pattern for matching with the white space character.

I know It’s very simple task but may be helpful for newbie who are not very familiar with regular expression and face that stupid problem of ALPHA_DASH

Xampp new version 1.6.3 has been released with the support of  PHP 5.3. Magic Quotes feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed.

The Earlier versions of Codeigniter has used magic quotes functions of PHP. So, be aware of that. If you haven’t update your CodeIgniter version to 1.7.2 . Your site may crash any time if your server has upgraded to PHP 5.3. You may see the following errors in your site Home Page:

Deprecated: Assigning the return value of new by reference is
deprecated in D:\SERVER\xampp\htdocs\imobiliar\system\codeigniter\Common.php
on line 130

Deprecated: Assigning the return value of new by reference is
deprecated in D:\SERVER\xampp\htdocs\imobiliar\system\codeigniter\Common.php
on line 136

A PHP Error was encountered

Severity: 8192

Message: Function set_magic_quotes_runtime() is deprecated

Filename: codeigniter/CodeIgniter.php

Line Number: 60

A PHP Error was encountered

Severity: 8192

Message: Assigning the return value of new by reference is deprecated

Filename: libraries/Loader.php

Line Number: 255

So, If you upgrade your Xampp and see all your CI projects are crashed then don’t be afraid. Just Upgrade your CI to version 1.7.2 which SVN version has been released and ready to download. I hope your problem will be solved. ūüôā

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.