Showing posts with label CodeIgniter. Show all posts
Showing posts with label CodeIgniter. Show all posts

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

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.

28 November, 2010

Codeigniter Library for getting Gmail Contact List

Today i needed to get the gmail contact list for a project that i am doing in codeigniter. For this is thought of making a library, so that it can be used easily. So, here in the complete library class fr getting gmail contact list.

if (!defined('BASEPATH')) exit('No direct script access allowed');

class GmailContacts_lib {

var $FEED_URL = "http://www.google.com/m8/feeds/contacts/default/full";
var $LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
var $username;
var $passwd;
var $postData = array();

function GmailContacts_lib($gUsername, $gPassword) {
//constructor function
$this->username = $gUsername;
$this->passwd = $gPassword;
}

function get_gmail_contacts() {
$emailLists = array();
//create an array for post data
$this->postData = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->username,
"Passwd" => $this->passwd,
"service" => "cp",
"source" => "anything"
);
//initialize the curl object
$curl = curl_init($this->LOGIN_URL);
//set the curl options
$this->set_curl_options($curl, CURLOPT_POST, true);
$this->set_curl_options($curl, CURLOPT_POSTFIELDS, $this->postData);
$this->set_curl_options($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$this->set_curl_options($curl, CURLOPT_SSL_VERIFYPEER, false);
$this->set_curl_options($curl, CURLOPT_RETURNTRANSFER, 1);

//following variable contains the responses
$response = curl_exec($curl);

//check if the user has logged in sucessfully
//and save auth key if logged in
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
if( !empty($auth)) {
$headers = array("Authorization: GoogleLogin auth=".$auth);

//make the request to google contacts feed with the auth key maximum contacts is 10000
$curl1 = curl_init($this->FEED_URL);

//passing the headers of auth key
$this->set_curl_options($curl1, CURLOPT_HTTPHEADER, $headers);
//return the result in a variable
$this->set_curl_options($curl1, CURLOPT_RETURNTRANSFER, 1);

//results response
$feed = curl_exec($curl1);
//parse the feed and return email list array
$emailLists = $this->parse_response($feed);
}
else {
$emailLists = array("Invalid Username/Password");
}
return $emailLists;
}

//function to set curl options
function set_curl_options($ch, $option, $value) {
//make the post TRUE
return curl_setopt($ch, $option, $value);
}

//function to parse response
public function parse_response($feed) {
$contacts = array();
$doc = new DOMDocument();

//load the XML response
$doc->loadXML($feed);
//check the entry tag
$nodeList = $doc->getElementsByTagName( 'entry' );

foreach($nodeList as $node) {
//children of each entry tag
$entry_nodes = $node->childNodes;
$tempArray = array();

foreach($entry_nodes as $child) {
//get the tagname of the child
$domNodesName = $child->nodeName;
switch($domNodesName) {
case "title":
{ $tempArray['fullName'] = $child->nodeValue; }
break;
case "gd:email":
{
if (strpos($child->getAttribute('rel'),'home')!==false)
$tempArray['email_1']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'work')!=false)
$tempArray['email_2']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'other')!==false)
$tempArray['email_3']=$child->getAttribute('address');
}
break;
} //end of switch for nodeNames
} //end of foreach for entry_nodes child nodes
if( !empty($tempArray['email_1'])) $contacts[$tempArray['email_1']] = $tempArray;
if( !empty($tempArray['email_2'])) $contacts[$tempArray['email_2']] = $tempArray;
if( !empty($tempArray['email_3'])) $contacts[$tempArray['email_3']] = $tempArray;
}
return $contacts;
}
}

And thats it. Hope this helps someone like me.

13 November, 2010

Jquery Ajax in CodeIgniter

The time I first started coding in codeIgniter, i had lots of confusions regarding
how to implemente ajax in codeigniter. I was using jquery for a project in codeIgniter,
and had a need to use jquery ajax in different sections of my project.
Since codeIgniter is MVC supportive open source framework, implementation of ajax in it is similar to usage of
ajax in other PHP MVC frameworks.
Here is how i started using ajax in codeigniter.
CodeIgniter has Model, Controller and Views (MVC).
So i started with a view file, user_notifications.php
//I had used jquery library for javascript,
//as this is one of the library I am confortable with
//include the jquery library script

function add_note() {
var note = $("#txtNote").val(); // this note value is from input type text with id as txtNote
if(note != "") {
//call the ajax function of jquery to post data to controller funcition
$.ajax({
type: "POST",
url: "user/members/add_note",
data: "&userId="+userId+"&add_user_note="+note,
success: function(responseTxt) {
alert(responseText);
return false;
}
});
}
return false;
}
....
....
in the view file we might have



In above code we are posting data using jqurey ajax function to a url specified in "url" variable
base_url() in codeigniter returns site's base URL as defined in config.php file
"user" is the folder name
"members" is the name of controller we are posting data to and
"add_note" is the function name in members controller

Now lets create a controller, members.php inside user folder

function add_note() {
//get the post data
$user_id = $this->input->post("userId");
$note_add = $this->input->post("add_user_note");
//add this note to database or process like you want
//the return successful or error message or something else that you want to, like
echo "Note Added Successfully...!";
}

The last echo message will be displayed by alert inside success function, with the message
passed from controller function as return as responseText.
So in this way we can use ajax with codeigniter.

19 September, 2010

Get current page from Codeigniter pagination

Once i had a simple problem to get current page number from codeigniter pagination. After some checks, i managed to get it working by simple one line of code. I hope this will help someone like me.

//here: $this->uri->segment(n) is the segment value that you pass when initializing pagination
//and $config['per_page'] is number of pages to be displayed during pagination initialization in codeigniter
$currentPage = floor(($this->uri->segment(n)/$config['per_page']) + 1);
echo "Current Page:".$currentPage;

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