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.

28 February, 2011

Working with question mark in url in codeigniter routing

Once i was working with Paypal payment integration (subscriptions) with codeigniter. Got the subscription part working but i was having problem when paypal redirected to my site after a successful payment.

My return url after successful payment from paypal was controller_name/get_success,
but Paypal added some extra info in this url and made it like:
controller_name/get_success?auth=some_auth_code
Since i had used

$config["enable_query_string"] = FALSE;
?>

this caused me problem, it was showing a 404 page. I tried fixing this problem with routing like,

$route["controller_name/get_success\?(:any})] = "controller_name/get_success";
?>

but this didnt work at all.
So, after some searching, i came up with a solution, and it was using hooks. Though we could use pre_controller hooks, but i opted using a pre_system hook, as:

Step 1:
//Inside application/config/config.php

$config['enable_hooks'] = TRUE;
?>

Step 2:
//inside application/config/hooks.php

$hook['pre_system'] = array(
'function' => 'remove_the_stuff',
'filename' => 'remove_get.php',
'filepath' => 'hooks'
);
?>

Step 3:
Created remove_get.php file inside application/hooks

function remove_the_stuff() {
if (isset($_GET['auth'])) {
define('AUTH', $_GET['auth']);
unset($_GET);
}
}
?>

Step 4:
Set up the uri_protocol in application/config/config.php

$config["uri_protocol"] = "REQUEST_URI";
?>

And thats it, its working without any problems.Hope this is useful.

15 February, 2011

Login to Hyves using cURL

Logging in to hyves using the API provided by them are great, but i had a different situation where i needed to login to hyves using curl. For this i googled through
but could not get any resources. So i thought of creating it on my own.

The code connects to hyves with curl. Its simple, we just need to use appropriate curl options getting hidden field name::value pairs from the hyves login page along with the form action. And we are done.

So here's the code.

//function to get hidden field name:value pairs from html page
function getHidden($formAsString) {
$hidEles="";
$doc=new DOMDocument();
$doc->loadHTML($string_bulk);
$xpath=new DOMXPath($doc);
$query="//input[@type='hidden']";
$hidData=$xpath->query($query);
foreach($hidData as $field) {
//type cast the value to string
$name=(string) $field->getAttribute('name');
$value=(string) $field->getAttribute('value');
$hidEles[$name]=$value;
}
return $hidEles;
}
//hyves mobile page url for login
$hyvesUrl = "http://www.hyves.nl/mini/?l1=mo";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $hyvesUrl);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPGET ,true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_REFERER, '');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$homepage = curl_exec($ch);

//get the action value of the login form
$searchStr = "/class=\"form\" action=\"(.*?)\"/";
preg_match($searchStr, $page, $matches);
$frmAction = $matches[1];

//get the hidden field name:value pairs from login page
$eles=getHiddenElements($homepage);
$eles['auth_username']="hyves-username";
$eles['auth_password']="hyves-password";
$eles['login']='Login';

//prepare post values
$els='';
$flag = false;
foreach ($eles as $name=>$value) {
if ($flag)
$els.='&';
$els.="{$name}=".urlencode($value);
$flag = true;
}

//now post the login form
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $form_action);
curl_setopt($ch, CURLOPT_POSTFIELDS,$els);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resLogin = curl_exec($ch);
echo $resLogin;
//and you are loggedin

So, in this way you can login to hyves using curl, and after logging in you can do
lots of other stuffs, like add new tips, blogs, send message, etc.

14 February, 2011

How to get all hidden elements from a form using php

I always had problem getting all the hidden elements of a form when using cURL. So thought of making a function that extracts all the hidden elements from a form when passed as a string.
Here's the function

function getHidden($form) {
$hiddenElements="";
$doc=new DOMDocument();
$doc->loadHTML($form);
$xpath=new DOMXPath($doc);

//use xPATH for quering the hidden elements in a form passes as string $form
$qry="//input[@type='hidden']";
$xData=$xpath->query($qry);

//loop thru all the data
foreach($xData as $value) {
//typecast the name and values as string to avoid xml object
$eleName=(string) $value->getAttribute('name');
$eleValue=(string) $value->getAttribute('value');
$hiddenElements[$eleName]=$eleValue;
}
return $hiddenElements;
}

?>

And thats it. The above function can be useful while doing a cURL using php to get form fields. Hope this helps someone

04 February, 2011

Facebook Share using cURL & PHP

I required a php script for facebook share using curl, found some but none of them worked for me. Found one script that was close to working, so i changed and added some codes in it and finally got it working. So following code snippet can be used for facebook share using curl in php.

The following code uses m.facebook.com for using the share feature. It first logs in a valid facebook user, gets the page after logging in, extracts hidden field values and form action used for posting message, then finally shares the message using curl.

$status = 'YOUR MESSAGE HERE';
$login_email = 'YOUR-EMAIL-ADDRESS';
$login_pass = 'YOUR-FACEBOOK-PASS';

//curl to login to facebook
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_exec($ch);

//get the page after logging in successfully
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($ch);

//get hidden values
$searchStr = "/name=\"post_form_id\" value=\"(.*?)\"/";
preg_match($searchStr, $page, $matches);
$post_form_id = $matches[1];

$searchStr2 = "/name=\"fb_dtsg\" value=\"(.*?)\"/";
preg_match($searchStr2, $page, $matches1);
$fbDtsg = $matches1[1];

$searchStr3 = "/name=\"charset_test\" value=\"(.*?)\"/";
preg_match($searchStr3, $page, $matches2);
$charsetTest = $matches2[1];

//get the posting url
$searchStr4 = "/id=\"composer_form\" action=\"(.*?)\"/";
preg_match($searchStr4, $page, $matches3);
$frmAction = $matches3[1];

//final post url
$postStatUrl = 'http://m.facebook.com'.$frmAction;

//finally post your message
curl_setopt($ch, CURLOPT_URL, $postStatUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS,'charset_test='.$charsetTest.'&fb_dtsg='.$fbDtsg.'&post_form_id='.$post_form_id.'&status='.$status.'&update=Share');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_exec($ch);
?>

And thats it. Share it.

03 February, 2011

Writing Distributable Code in PHP

Several stuffs should be taken care of when you are working in a team,
or writing code for public release. Those stuffs can be:

a) Code should be easily readable.
b) Code should be extendable.


Well, that's what came to my mind for now. Debugging or extending someone else's code can be the toughest and frustrating task if the previous developer have not coded keeping above two points in mind.

So, if you want to stop troubling other's and yourself of-course, then you should make hebit of writing distributable code. The terminology 'distributable code' means nothing but following a good programming practice. At first, following a programming practice may tend to be uneasy, but as you keep on working you make it a habit.

Following are some of the programming practice that can be followed.
1)Select a Coding Standard
A coding standard can be:
a) Naming conventions (for files, variables, classes, etc)
b) Setting indentation rules
c) Commenting well and documentation

2)Writing Code in OOP
Start habit of Object oriented programming. Though experts say OOP tends to be costly to an application performance. But, comparitively they are cheaper then
web developers. Object Oriented code can be easily reused and extended. Though OOP may not give performance hike but it definitely give's you the faster better code as compared to slower better code.

So, write Distributable code and help yourself and others.

28 January, 2011

Check value exists in multidimensional array

Most of the times we are playing with arrays in php. And it can be troublesome when we have to check for value in multidimensional array. I get into such a situation every often. I used to loop through the array to check for the existence of value.

So, i thought of making a function that checked for the existence of a value in a multi array. I am much happier using this function rather than looping through arrays making my time worse.

Following code simplifies checking of a value in multi-array in php.

//function to check if a values exists in multidimensional array
function in_multi($searchFor, $array) {
foreach($array as $key => $value) {
if($value == $searchFor) {
return true;
}
else {
if(is_array($value)) if(in_multi($searchFor, $value)) return true;
}
}
return false;
}
//test array
$testArr = array(
0 => array(
0 => array(
"10" => 20,
"20" => 40
),
1 => array(
"a" => 555,
"b" => 152
)
),
1 => array(
0 => 999,
1 => 2024
)
);


$isThere = in_multi(152, $testArr);
if($isThere) {
echo "Found";
}
else {
echo "Not Found";
}
?>
And we are done.

27 January, 2011

How to Sync php calendar events to Outlook 2007

I found lots of sites that showed how to sync events from my custom calendar to
Microsoft Outlook 2007 using PHP. But could not make any of it work my way. I
somehow managed to make it work. Microsoft Outlook 2007 uses iCal files, i.e.
Internet Calendar files, so with the help of some sites searched using Google
I created an iCal file adding my customs calendar events in it.
Here is the code snippet for the same.

$userTimeZoneName = "America/New_York";
$userTimeZoneAbbr = "GMT";
$eventSummary = "This is summary of event";

$eventStartDate = date("Ymd", time()); //like 20110112
$eventStartTime = date("His", time()); // like 163000
$eventEndDate = "20110128"; //you can set your own end date in Ymd format
$eventEndTime = "1223000"; //you can set your own end time in His format

$eventDescription = "Some event description here";
$eventsLocation = "Nepal, Kathmandu";
$eventId = "20"; //this can be your event id


$ical = "BEGIN:VCALENDAR\n";
$ical .= "PRODID:-//Sudhir/SudhirWebCal//NONSGML v1.0//EN\n";
$ical .= "VERSION:2.0\n";
$ical .="CALSCALE:GREGORIAN\n";
$ical .="METHOD:PUBLISH\n";
$ical .="X-WR-CALNAME:SudhirCal\n";
$ical .="X-WR-TIMEZONE:".$userTimeZoneName."\n";
$ical .="X-WR-CALDESC:Commonfig Events\n";
$ical .="X-PUBLISHED-TTL:PT5M\n";
$ical .="BEGIN:VTIMEZONE\n";
$ical .="TZID:".$userTimeZoneName."\n";
$ical .="X-LIC-LOCATION:".$userTimeZoneName."\n";
$ical .="BEGIN:DAYLIGHT\n";
$ical .="TZOFFSETFROM:+0000\n";
$ical .="TZOFFSETTO:+0100\n";
$ical .="TZNAME:".$userTimeZoneAbbr."\n";
$ical .="DTSTART:19700329T010000\n";
$ical .="RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\n";
$ical .="END:DAYLIGHT\n";
$ical .="BEGIN:STANDARD\n";
$ical .="TZOFFSETFROM:+0100\n";
$ical .="TZOFFSETTO:+0000\n";
$ical .="TZNAME:GMT\n";
$ical .="DTSTART:19701025T020000\n";
$ical .="RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n";
$ical .="END:STANDARD\n";
$ical .="END:VTIMEZONE\n";
$ical .="BEGIN:VEVENT\n";
$ical .="SUMMARY:".$eventSummary."\n";
$ical .="DTSTART:".$eventStartDate."T".$eventStartTime."\n";
$ical .="DTEND:".$eventEndDate."T".$eventEndTime."\n";
$ical .="DESCRIPTION;ENCODING=QUOTED-PRINTABLE:".str_replace("\r", "=0D=0A",$eventDescription)."\n";
$ical .= "LOCATION:".$eventsLocation."\n";
$ical .="UID:".sha1($eventStartDate.$eventId)."example.com\n";
$ical .="LAST-MODIFIED:20110119T123850Z\n";
$ical .="STATUS:PRIVATE\n";
$ical .="END:VEVENT\n";
$ical .="END:VCALENDAR";

//the line X-PUBLISHED-TTL:PT5M; sets the outlook calendar refresh time to 5 minutes
//so all your events will be automatically synchronized
//to your outlook calendar every 5 minutes t
//this can be increased to 2 hours like X-PUBLISHED-TTL:PT120M;

echo $ical;

//this will output the events in outlook calendar format
?>
The above code can be added inside a function and can be accessed using a link like
webcal://yourdomain.com/your_function_for_ical
In this way we can create calendar files for outlook 2007 and synchronize events of
custom PHP calendar with Microsoft Outlook 2007 calendar.
Hope it helps someone.

Coverflow effect with Jquery

I was searching for a Apple's like coverflow effect using jQuery, and got into the following post in stackoverflow.
Here's the link,
http://stackoverflow.com/questions/67207/apple-cover-flow-effect-using-jquery-or-other-library

Put it out with a perdurable