08 September, 2010

Load all class at once in php

Loading all the classes at once in php can be done by a simple code. If we have requirement to load lots of php classes
at once then this can be really boring. So in order to load all class at once in php we could write some code. Following
php code does the job.

function loadModules($dir) {
//create an array to hold the class names
$classes = array();
//usign DirectoryIterator class of php to get the handle of directory that contains the classes
$dh = new DirectoryIterator($dir);
//loop through each file
foreach($dh as $file) {
//check if the file is not a directory and ends with a .php extension
if($file->isDir() == 0 && preg_match("/[.]php$/", $file)) {
//include the class
include_once($dir."/".$file);
$class = preg_replace("/[.]php$/","", $file);
$classes []= $class;
}
}
return $classes;
}
?>

05 September, 2010

Integrating Videowhisper in CodeIgniter

Some times ago, i confronted a problem of integrating videowhisper with CodeIgniter. Searched through videowhisper forums but could not get exact solution, though i managed to do it using info regarding integration for plain php code.
I hope this might help someone like me.
Lets say we have a project folder named "test"
Step 1:
Add the "videowhisper_conference.swf" file in you root folder (project folder test) and its necessary folders like "uploads", "emoticons", etc. in the same folder

Step 2:
Copy the contents of "videowhisper_conference.php" into your view file, where you want to display the video.

Step 3:
Create function in your controller for each of the file, such as videologin for vc_login.php, videostatus for vc_status.php file. Do this for all the .php files that you require.

Step 4:
Add following code in you .htaccess file
RewriteCond %{QUERY_STRING} room_name(.*)

RewriteRule vc_login.php(.*) folder_name/controller_name/videologin/%1? [L]
RewriteRule vw_rooms.php(.*) folder_name/controller_name/videorooms/%1? [L]
RewriteRule vw_files.php(.*) folder_name/controller_name/videofiles/%1? [L]
RewriteRule vc_status.php(.*) folder_name/controller_name/videostatus/%1? [L]
and so on for all the files that you need.

You are done.
I've mentioned general steps in this case. You need to pass on the logged in user id and other required values accordingly.
Hope it helps.

25 August, 2010

Unset empty elements in Array

It is quite easier to unset empty element(s) in an array in php. Following code will do the work.

//this is a test array
$testArr = array(1 => "First", 2 => "", 3 => "Third", 4 => "", 5 =>"Fifth");
//loop through the array and remove empty elements
foreach($testArr as $key => $value) {
if(empty($value)) {
unset($testArr[$key]);
}
}
//view the array with empty elements removed
print_r($testArr);
?>

08 July, 2010

Integrating Zend with CodeIgniter

Last day, I had to integrate Zend Framework with Codeigniter. This came out to be quite easier then i thought. So here are the steps for integrating zend
framework with codeigniter.

Step 1: Copy the Zend folder from inside the library folder of Zend Framework

Setp 2: Create a folder inside your system, such as ../system/zf.

Step 3: Create a helper file like: zf_helper.php and place it into ../system/application/helpers/
Here is the code for zf_helper.php file

//For Linux OS
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . BASEPATH . '/zf/');
require_once 'Zend/Loader.php';

//For windows OS
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . str_replace('/', '\\', BASEPATH) . 'zf\\');
require_once ('Zend/Loader.php');
?>


Step 4: Add this helper to your ../system/application/config/autoload.php file

$autoload['helper'] = array('url', 'form', 'date', 'zf'); //zf is the helper that we have added for zend framework integration
?>

Step 5: Now you can use any modules of Zend Framework from CodeIgniter, like in a controller file

class SomeTest extends Controller {
//in some function
//.....
//....
//....
function someFunction() {
//load Zend Classes
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
$username = "someuser@gmail.com";
$password = "somepassword";
$gCalen = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($username, $password, $gCalen);
$gCalen = new Zend_Gdata_Calendar($client);
//and so on
}
}
?>

Show this is how Integrating Zend with CodeIgniter works

06 July, 2010

Get Google Calendar Events using cURL

Once i needed to get all the google calendar events to my site, i.e. getting all the events that we added to google calendar to our custom calendar. After some reading, i found some helpful tips for doing this and here is the code. This is just a snippet. For logging in to gmail account please check my other post. The authentication token obtained after successful login is used in the following code.
So, what this code does is, it gets google calendar events using cURL. The code is simple. Just the retrieving of xml feed of google calendar events is done here, after this we can parse the xml and display all the events to our custom page after some formatting. Checkout the code.

$fAuth = "authentication-token-obtained-after-successful-login";
$arr_headers = array();
$arr_headers[] = "Host: www.google.com";
$arr_headers[] = "MIME-Version: 1.0";
$arr_headers[] = "Accept: text/xml";
$arr_headers[] = "Authorization: GoogleLogin auth=".$fAuth;
$arr_headers[] = "Content-type: application/atom+xml";
$arr_headers[] = "Cache-Control: no-cache";
$arr_headers[] = "Connection: Keep Alive \r\n";

$url = "http://www.google.com/calendar/feeds/emialadd%40gmail.com/private/full";
$ch = curl_init();


curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_headers);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4b) Gecko/20040612 Mozilla Firebird/0.9");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$resFin = curl_exec($ch);
echo $resFin;
?>

05 July, 2010

Accordion style show/hide divs using jQuery

This is just a start, but thought it might be of some help to others, so posted the code snippet. The code uses class for divs and anchor tags. This is a simple demo of accordion like tabs, but i've just done show and hide of divs using jQuery selectors.
When a link above a div is clicked, the div immediately below the anchor tag is displayed and all other divs are hidden.
Some animation can also be used in place of just show hide.If none of other divs are displayed as block then the current div is not closed. And by default first div is displayed when page is loaded.
Check out the following code snippet

$(document).ready(function() {
//display by default the first div content
$(".acc:first").css('display', 'block');
//attach click event to anchor tags
$(".atest").click(function() {
//check for the display block or none of the immediate div next to anchor tag
var displayStatus = $(this).next().css('display');
if(displayStatus == "block") {
var otherDivsStatus = $(".acc").not($(this).next()).css('display');
if(otherDivsStatus == "block") {
$(this).next().hide('slow');
}
}
else {
//hide all the divs except for the current div
$(".acc").not($(this).next()).hide('slow');
$(this).next().show('slow');
}
});
});
/*
Just a test html, this can be changed as needed

First Block

This is first div

Second Block

This is second div

Third Block

This is third div


*/

Check All - Uncheck All multiple checkboxes using jquery

Sometimes later, i had to check and/or uncheck multiple checkboxes having same name being displayed dynamically). I have one checkbox for Check/Uncheck All, and depending on that, i had to check or uncheck other checkboxes. And if any one of the checkboxes, besides main checkbox, was checked or unchecked, then i would have to check or uncheck the main checkbox as well.
The text i have writte here might seem little confusing than the original source code, but the main point is i had to check/uncheck multiple checkboxes at once. So here is the jquery code that i wrote for doing the same.

$(document).ready(function() {
//get count of checkboxes with the same name
var countBoxes = $("input[name='chkTest[]']").size();
//move through each checkbox
$("input[name='chkTest[]']").each(function() {
$(this).click(function() {
//get the state, checked or not, i.e. true or false
var state = $(this).attr("checked");
//get the length of checked checkboxes
var chkedLength = $("input[name='chkTest[]']:checked").length;
//make the checked or unchecked state
var chkAllState = (chkedLength == countBoxes) ? true : false;
//now apply the state to main checkbox
$("input[name='chkAll']").attr("checked", chkAllState);
});
});
//this code checks or unchecks all sub-checkboxes depending on checked state
$("input[name='chkAll']").click(function() {
var chkAllStatus = $(this).attr('checked');
$("input[name='chkTest[]']").attr("checked", chkAllStatus);
});
});

Same height sub-divs using jQuery

Previous day i had to make height of all the child divs same. Actually i had 3 divs, with different height according to dynamic content, inside a main div, but i needed to make of all those child divs same irrespective of the content they had. So, i figured it out using s simple jquery code.
This code actually checks for a div that has maximum height, and then applies that max height to all the divs that is contained inside the main div. Check out the following code snippet.

//include your jquery.js file here
$(document).ready(function() {
//make a new array for storing the heights temporarily
var heightArr = new Array();
//loop through each of the child divs of parent div,
//i've used class of div, but it can be replaced with id as well
$(".mainDiv").children().each(function() {
var divHeight = $(this).height();
//push the height to array
heightArr.push(divHeight);
});
//this is a function to get maximum value from an array
Array.max = function(array) {
return Math.max.apply(Math, array);
}
var maxHeight = Array.max(heightArr);
//now apply the maxHeight to all the divs css
$(".mainDiv").children().each(function() {
$(this).css('height', maxHeight);
});
});

23 June, 2010

ucfirst in mysql

Its quite hard to convert first character of a string to capital in mysql. Same problem existed for me. I however managed to work it out using following sql query. This query is used to capitalize first letter of a string to upper case similar to ucfirst in php.

SELECT CONCAT(upper(substr("test this one.", 1, 1)),"", LOWER(SUBSTR("test this one.", 2, length("test this one."))));

In above query, the string "test this one." can be replaced by the field name while performing query in database.

14 June, 2010

Find if multi-dimensional array is empty

Checking for emptinessin quite simple using php. Following function can be used to check if a multidimensional array is empty or not.
The code loops through all the values in multi-dimensional array to check for empty values.

$food = array(
'fruits' => array('', '', ''),
'veggie' => array('', '', ''),
"test" => ""
);
//set the empty count to 0
$countEmpty = 0;
//set number of keys count to 0
$countKey = 0;
foreach($food as $key => $val) {
if(is_array($val)) {
//loop through each values inside
foreach($val as $key1 => $val1) {
$val = trim($val);
if(empty($val1)) {
//empty value-- increment the empty value count
$countEmpty++;
}
//increment the key count
$countKey++;
}
}
else {
$countKey++;
$val = trim($val);
if(empty($val)) {
$countEmpty++;
}
}
}
if($countKey == $countEmpty) {
echo "Array is empty..!";
}
else {
echo "Array contains".($countKey - $countEmpty)." value(s)";
}
echo "
";
echo "Keys:".$countKey."
";
echo "Empty:".$countEmpty;
?>