24 June, 2012

Get controller name in view with codeigniter

Getting controller name in view with codeigniter is simpler than anything else. Just use one line of the code and you get the name of controller in view in codeigniter. Use this in any view file:


$controllerName =  $this->router->class;
echo "My controller name is:".$controllerName;

25 July, 2011

Caching in PHP

The term Caching refers to storing of data for later usage. Commonly used data can be cached it can be accessed faster and caching in PHP can be easier task as well, if you know what you are doing. Following code snippet demonstrates File Caching in php in which data is written to the file by caching process.

class CacheFile {
protected $fPointer;
protected $fileName;
protected $expirationTime;
protected $tempFileName;

//constructor function
//pass in the filename along with optional expiration
public function __construct($fileName, $expiration = false) {
$this->fileName = $fileName;
$this->expirationTime = $expiration;
$this->tempFileName = "$filename.".getmypid();
}

public function get() {
//check for expiration and return contents of cache file
if($this->expirationTime) {
//get the file status
$status = @stat($this->fileName);
if($status[9]) {
//check the filetime
if(($modified + $this->expirationTime) < time()) {
@unlink($this->fileName);
return false;
}
}
}
return file_get_contents($this->fileName);
}

public function put($fileBuffer) {
if(($this->fPointer == fopen($this->tempFileName, 'w')) == false) {
return false;
}
fwrite($this->fPointer, $fileBuffer);
fclose($this->fPointer);
rename($this->tempFileName, $this->fileName);
return true;
}

//remove the cache file
public function remove() {
@unlink($this->fileName);
}

//start the caching process
public function startOutputBuffer() {
if(($this->fPointer = fopen($this->tempFileName, 'w')) == false) {
return false;
}
ob_start();
}

//end the caching process
public function endOutputBuffer() {
//get the output bufer contents
$bufferContents = ob_get_contents();
ob_end_flush();
if(strlen($bufferContents)) {
fwrite($this->fPointer, $bufferContents);
fclose($this->fPointer);
rename($this->tempFileName, $this->fileName);
return true;
}
else {
fclose($this->fPointer);
@unlink($this->tempFileName);
return false;
}
}
}
?>

And the File Cache class cane be used as follows:

require_once('CacheFile.php');
$cacheData = CacheFile($pathToCacheFile);
//check if the string exists in cache
if($string = $cacheData->get()) {
var_dump($string);
}
else {
//start caching process
$cacheData->startOutputBuffer();
?>
//your page data included here
$cacheData->endOutputBuffer();
}
?>

In this way we can implement Caching in php.

04 June, 2011

Override CakePHP model's find method

By default CakePHP's find method of model allows us to use four types of find, viz
"all", "first", "count" and "list", but in some cases we need to find something using
some other type, like find all the pending blog posts of a user.

In such case we can just override the cakePHP's model find method in our model to suit our needs. Lets say we have a model named Post for posts table in database. So, our overridden model would look like:

class Post extends AppModel {
//relationships
var $belongsTo = array('User');

function find($type, $queryData = array()) {
switch($type) {
case "pending":
//field is_published is tinyint with value 1 OR 0 for published or pending respectively
$pending = $this->find('all', array('conditions'=>array('Post.is_published' => 0), 'contain' => array('User')));
return $pending;
break;
default:
//call the default find method with all related parameters
return parent::find($type, $queryData);
}
}
}
?>

So now in function of our controller, we can use this as:

//get the id of logged in user
$userId = $this->Auth->user('id');
$pendingPosts = $this->Post->find('pending', array('user_id' => $userId));
?>

And thats it.

31 May, 2011

Image Browse And Upload feature in ckEditor

ckEditor version 3.6 "by default", may be previous versions as well hides the file browse and upload function, but its quite easy to make them display if we know where to change it.
Go to folder ckeditor\plugins\image\dialogs\, in there you will find a file image.js, open it in editor and search the file for id:'Upload', you will see that, its set as id:'Upload',hidden:false, set it as id:'Upload',hidden:true, and refresh your page where you have added ckEditor, you will be able to see the Upload tab with Browse button in it.

Thats it.

23 May, 2011

Javascript Functions Flexibility

In Javascript, everything is an object. Functions in Javascript are said to be first-class objects, that can be passed as arguments to other functions, stored as variables, created at run-time,etc.

Anonymous functions without parameters that run immediately.

(function() {
var one = 1;
var two = 2;
alert(one+two);
})();

In above anonymous function, the parenthesis at the end indicates that this function will be run immediately without being assigned to any variable.

Anonymous functions with parameters that run immediately.
The parenthesis at the end can have some parameters as well. Such as,

(function(one, two) {
alert(one+two);
})(1, 2);

Or, if you want to assign the value to some variable then,

var three = (function(one, two) {
alert(one+two);
})(1, 2);
alert(three); //and output is 3


Assign Attribute to Functions in Javascript
In Javascript we can modify classes after they have been defined and objects after they have been created. Lets take an analogy, we have a car class,

function Car(name, model) {
this.name = name;
this.model = model;
}
Car.prototype = {
getName: function() {
return this.name;
},
getModel: function() {
return this.model;
}
}
//instantiate the class now
var benz = new Car('Benz', 1969);
var bmw = new Car('Bmw', 1984);

//now modify the class
Car.prototype.getPrice = function() {
return "Price for " + this.getName() + "is " + 20000;
};

//now modify the specific object instance
benz.showPrice = function() {
alert(this.getPrice());
};

In above example, we added a new function getPrice() after two object instances for the class are created. And, benz object instance gets showPrice() function in addition to other functions of the class, but bmw object instance wont get the showPrice() function in this case. This feature is called Object Mutability.
This is just few examples that tend to focus on flexibility of javascript functions.

10 May, 2011

REST client library using CodeIgniter

Using REST in applications makes life easier to some extent. And using REST in codeigniter can be easier. There exist some REST libraries in codeigniter but somehow they seem to have lots of code and features which is not required in my case. I'm not degrading existing codeigniter REST libraries, they are excellent codes
developed by experts, but i wanted a simple REST client using Codeigniter, so thought of coding my own.
Following is the code for REST client library in codeIgniter, that suits simple needs.


class Rest_Lib {

private $useCurl;
private $userAgent = "Rest";

/*
* constructor function
*/
function Rest_Lib() {
//check if curl function exists
if(function_exists('curl_init')) {
$this->useCurl = TRUE;
}
else {
$this->useCurl = FALSE;
}
}

/*
* GET method
* @param string $url : this is the service url
* @param array $arr: this is the key value
* @return string : resulting response of GET method
*/
public function get($url, $arr) {
$str = '?';
if(is_array($arr)) {
foreach($arr as $key => $value) {
$str .= urlencode($key) . '=' . urlencode($value) . '&';
}
}
else {
$str .= $arr;
}
$url .= $str;
if($this->useCurl) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
}
else {
$options = array(
'http' => array(
'method' => 'GET',
'header' => 'User-Agent:' . $this->userAgent . '\r\n'
)
);
//create and return stream context with options
$streamContext = stream_context_create($options);
$fh = file_open($url, 'r', FALSE, $streamContext);
$response = fpassthru($fh);
fclose($fh);
}
return $response;
}

/*
* POST method
* @param string: $url: service url
* @param string $postData: request data
* @return response
*/
public function post($url, $postData) {
if($this->useCurl) {
$curlHeaders = array(
'Content-Type: application/x-www-form-urlencoded'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
$response = curl_exec($ch);
curl_close($ch);
}
else {
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'User-Agent: ' . $this->userAgent . '\r\n',
'Content-Type: application/x-www-form-urlencoded' . '\r\n',
'Content-Length: ' . strlen($postData) . '\r\n',
'Content' => $postData
)
);
$streamContext = stream_context_create($options);
$fh = file_open($url, 'r', FALSE, $streamContext);
$response = fpassthru($fh);
fclose($fh);
}
return $response;
}

/*
* PUT method
*
*/
public function put($url, $putData) {
if($this->useCurl) {
$fh = fopen('php://memory', 'rw');
fwrite($fh, $putData);
rewind($fh);

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
curl_setopt($ch, CURLOPT_INFILE, $fh);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putData));
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_PUT, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
fclose($fh);
}
else {
$options = array(
'http' => array(
'method' => 'PUT',
'header' => 'User-Agent: ' . $this->userAgent . '\r\n',
'Content-Type: application/x-www-form-urlencoded' . '\r\n',
'Content-Length: ' . strlen($putData) . '\r\n',
'Content' => $putData
)
);
$context = stream_context_create();
$fh = file_open($url, 'r', FALSE, $context);
$response = fpassthru($fh);
fclose($fh);
}
return $response;
}

/*
* DELETE method
*/
public function delete($url, $arr) {
$str = '?';
if(is_array($arr)) {
foreach($arr as $key => $value) {
$str .= urlencode($key) . '=' . urlencode($value) . '&';
}
}
else {
$str .= $arr;
}
$url .= $str;
if($this->useCurl) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'delete');
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
$response = curl_exec($ch);
curl_close($ch);
}
else {
$options = array(
'http' => array(
'method' => 'DELETE',
'header' => 'User-Agent: ' . $this->userAgent . '\r\n'
)
);
$context = stream_context_create($options);
$fh = file_open($url, 'r', FALSE, $context);
$response = fpassthru($fh);
fclose($fh);
}
return TRUE;
}
}
?>

04 May, 2011

How to ImageMagick using PHP

ImageMagick can be used to create and edit images dunamically and display the results online or locally at our desired URLs. It offers lots of features, such as crop, resize, rotate, flip, blur, sharpen, inserting texts, and lots more, using its syntax properly.
And we can do all this stuffs using PHP. In order to use ImageMagick with PHP we can use PHP's function for executing external programs, which is exec and system. Other such functions also exist in PHP but the two mentioned above have the highest
priority.
The usage format is:

echo exec(string command [, array &output ]);
?>

In its simplest form, ImageMagick can be used as:

$firstImg = "test.bmp";
$finalResult = "test2.png";
exec("path_tp_image_magick\imagemagick\convert {$firstImg} {$finalResult}");
?>


Basically, the above function converts test.bmp to test2.png, i.e changes the file format.
Some of the basic stuffs that can be done using ImageMagick

Stuff 1: How to get width and height of image using ImageMagick in php

$dimensionsArr = array();
$inputImage = "full_path_to_input_image.jpg";
//get image width and height
exec("full_path_to_image_magick/identify -format \"%w\n\%h\" {$inputImage}", $dimensionsArr);
?>

In above case width and height of image are stored in $dimensionsArr array.

Stuff 2: How to Watermark an Image using ImageMagick in PHP

$inputImage = "full_path_to_input_image.jpg";
$waterMarkText = "Watermark Me";
$outputImage = "full_path_to_output_image.jpg";
exec("full_path_to_image_magick/composite -watermark 30% -gravity northeast {$inputImage} {$waterMarkText} {$outputImage}");
?>


Stuff 3: Crop an image using ImageMagick in PHP

$firstImg = "first.jpg";
$output = "cropped.jpg";
exec("E:\wamp\www\im\imagemagick\convert {$firstImg} -crop 120x80+160+80 {$output}");
?>

In above code what we did is we cropped an image "first.jpg" to set width of 120px and height of 80px and the cropping is started from 160x80 coordinate. Or a better way of cropping images can be done as:


$firstImg = "first.jpg";
$output = "cropped.jpg";
exec("E:\wamp\www\im\imagemagick\convert {$firstImg} -shave 120x80 {$output}");
?>

What above code does is, it cuts the borders with the values we defined in width X height parameters.

Stuff 4: Rotate Image using ImageMagick in PHP

$firstImg = "first.jpg";
$rotated = "rotated.bmp";
exec("E:\wamp\www\im\imagemagick\convert {$firstImg} -rotate 90 {$output}");
?>

Above code we used value -rotate 90 to rotate the image at 90 degrees, and saved the output in bmp

Stuff 5: Resize an image using ImageMagick in PHP

exec("E:\wamp\www\im\imagemagick\convert first.jpg -resize 10% -sample 500% first_new.png");
?>

The above code resizes first.jpg to 10% of its actual size with sampling at 500% and saves to "first_new.png"

Stuff 6: Extract frames from animated image using ImageMagick in php
One of the exciting feature that ImageMagick has is, we can extract the frames from an animated image file.
For that we can write a simple one-line command as:

$animatedImage ="animated.gif";
exec("E:\wamp\www\im\imagemagick\convert {$animatedImage} +adjoin animated_Image%02d.gif");
?>

The above code extracts frames from the animated image "animated.gif" and saves it as "animated_Image1.gif", "animated_Image2.gif", etc for each frame.

These are just some of the features that ImageMagick offers, there's lot more to check out. Above code snippets can act as a good start prior to delving into the ImageMagick commands in detail.

02 April, 2011

Login to Yahoo mobile using curl

Once i had to login to yahoo mobile for some calendar events manipulation, but since yahoo does not have any api for doing such stuffs so thought of giving it a try using curl. After some tests and hit & triali was able to login yo yahoo mobile
using curl and do my necessary calendar events manipulation.
Below is the code snippet for logging in to yahoo mobile using curl.

$mCookie = "mcookie.cookie";
$reffer = "http://m.yahoo.com/calendar";
$mUrl = "http://m.yahoo.com/calendar";
$ch = curl_init();
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt($ch, CURLOPT_URL, $mUrl);
curl_setopt($ch, CURLOPT_GET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $mCookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, $mCookie);
$mRes = curl_exec($ch);

//get the hidden fields

preg_match_all ( "/id=\"LoginModel\" action=\"(.*)\"/", $mRes, $formActionArr);
preg_match_all ( "/name=\"_authurl\" value=\"(.*?)\"/", $mRes, $authUrlArr);
preg_match_all ( "/name=\"_done\" value=\"(.*?)\"/", $mRes, $doneArr);
preg_match_all ( "/name=\"_ts\" value=\"(.*?)\"/", $mRes, $tsArr);
preg_match_all ( "/name=\"_crumb\" value=\"(.*?)\"/", $mRes, $crumbArr);

$authUrl = $authUrlArr[1][0];
$doneUrl = $doneArr[1][0];
$ts = $tsArr[1][0];
$crumb = $crumbArr[1][0];
$signIn = urlencode("Sign In");
$username = "yahoo_username";
$password = "yahoo_password";
$loginUrl = "https://mlogin.yahoo.com/w/login/auth?.ts=".$ts."&_httpHost=m.yahoo.com&.intl=NP&.lang=en";
$postFields = "_authurl=".$authUrl."&_done=".$doneUrl."&_sig=&_src=&_ts=".$ts."&_crumb=".$crumb."&_pc=&_send_userhash=0&_appdata=&_partner_ts=&_is_ysid=&_page=secure&_next=&id=".$username."&password=".$password."&__submit=".$signIn;

//now post the hidden fields
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $mCookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, $mCookie);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
$postRes = curl_exec($ch);
echo $postRes;
//we are logged in now
?>

Thats it, Hope this helps someone.

24 March, 2011

How To Display Data in a Grid using ExtJS

Grids in ExtJs are one of the most widely used components. Grids provide a better way to present your data to the end-users in an easy-to-understand manner. ExtJs Grids are user friendly, and have different customization options and events so that it can be used in your own way.
ExtJs Grids are similar to spreadsheets containing rows and columns. So, in order to display data in grid using ExtJs we need two Ext components.
1) A Grid Panel, for displaying data
2) A Store, which is like database to keep track of the data.

Now we write the javascript code for displaying data in grid

//load the required extjs files and inside script tag add the following
Ext.onReady(function() {
//first we need to add data store which is to be displayed in the grid
//so adding the data store for the grid
var firstStore = new Ext.data.Store({
//now add the relevant data
data: [
[
"Sudhir Bastakoti",
"1983-01-17",
"Male",
"sudhirbas@gmail.com",
"sudhir.bastakoti"
],
[
"John Doe",
"1978-02=04",
"Male",
"john@doe.com",
"john.doe"
],
[
"Joane Doe",
"1985-05-24",
"Female",
"joane@doe.com",
"joane.doe"
]
], //end of add data
//now add a reader; in this case we are using Array Reader of ExtJs to read the data
reader: new Ext.data.ArrayReader({id: 'id'}, [
'id',
'full_name',
{name: 'birth_date', type: 'date', dateFormat: 'Y-m-d'},
'gender',
'email',
'skype'
]
}); //end data store

//finally display the Grid Panel
var firstGrid = new Ext.grid.GridPanel({
renderTo: document.body, //grid in body; ID of a div can also be used
frame: true, //just adds a border to Grid Panel, not compulsory though
title: 'User Information', //as the name suggests; title of Grid
height: 200,
width: 250,
store: firstStore, //name of data store that contains data and reader confs
columns: [
{header: "User Name", dataIndex: 'full_name'},
{header: "Birth Date", dataIndex: 'birth_date', renderer: Ext.util.Format.dateRenderer('m/d/Y')},
{header: "Gender", dataIndex: 'gender'},
{header: "User Email", dataIndex: 'email', sortable: true},
{header: "Skype Add", dataIndex: 'skype'},
] //enf of column field
});
});

Add above javascript code in your html file and run in browser , you will be
seeing a grid with data added from store.

'renderer' in column field is for data formatting. In our case its used to format date to m-d-Y format. We can use some callback function instead of that. The grid has lots of built-in features which can be checked in ExtJs Manual.

19 March, 2011

Secure a page using php

By default php script runs on port 80 unless changed, but i had to secure a page so that it could run only on secure port i.e. 443. So what i did was used a code to force to run a page on secure port i.e. https which uses port 443, Here's what i did:

$serverPort = $_SERVER['HTTP_PORT'];
//check if its not secure port
if("443" != $serverPort) {
header("Location: https://".$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit;
}
?>

So, the above code ensures that the page runs under https i.e. port 443 and
is securely displayed. Hope it helps someone.