30 November, 2010

How to integrate Paypal Subscriptions using PHP

After lots of googling, i was on right track to integrate paypal subscriptions using php. So thought, this might be of some help to others as well. Here is how i integrated the paypal subscriptions in php.
Step 1: Create a paypal sandbox account from www.developer.paypal.com, if you dont have it else login to it.
Step 2: Create a test account (Preconfigured Account link) as a buyer.
Step 3: Verify the account if status says 'Unverified'.
Step 3: Create a test account (Preconfigured Account link) as a seller.
Step 4: Create a form for subscriptions payment in paypal as following code:
This is the form that is submitted to paypal (sandbox for test)


//cmd is _xclick-subscriptions for subscription





//amount is USD 300

//monthly; can use Y for annual subscription


//setting rm to 2 and using return will send the response as post values








You need not set any IPN path from your sandbox account, because adding "notify_url" to the form will override the account default settings.

Step 5: Now to the ipn.php page

$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach($_POST as $i => $v) {
$postdata .= $i.'='.urlencode($v).'&';
}
$postdata .= 'cmd=_notify-validate';
$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
}
else {
$web['port'] = 80;
$ssl = '';
}
$fp = @fsockopen($ssl.$web['host'], $web['port'], $errnum, $errstr, 30);
if (!$fp) {
echo $errnum.': '.$errstr;
}
else {
fputs($fp, "POST ".$web['path']." HTTP/1.1\r\n");
fputs($fp, "Host: ".$web['host']."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($postdata)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");

while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
}
fclose($fp);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
if(isset($_REQUEST["txn_type"]) && (strtolower($_REQUEST["txn_type"]) == "subscr_payment") || (strtolower($_REQUEST["txn_type"]) == "subscr_signup")) {
//update database, send notification or do whatever here
}
else {
//the subscription type can be something else
}
}
else {
//this is not valid payment
//so log some error here
}
}

And success and cancel page can be done easily.
And thats it, hope this helps someone.

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.

18 November, 2010

Subtract hours from date in php

One of my friend asked me how to subtract hours from date in php. The subtraction
could be hours or days. So here is what i did for him, to subtract hours from date
in php.
Lets say we need to subtract two hours from current date, then

//get today's date
$today = date("Y-m-d H:i:s", time());
$hours = 2;
//first convert today's date to timestamp, as
$strTodayDate = strtotime($today);
//now subtract hours from date
$subtractedTimeStr = strtotime("- $hours hours", $strTodayDate);
//now get the resulting date, i.e. date prior to 2 hours from today
$finalDate = date("Y-m-d H:i:s", $subtractedTimeStr);
echo $finalDate;

And thats it. To subtract days from date use days in place of hours in above code as:

$days = 2;
$subtractedTimeStr = strtotime("- $days days", $strTodayDate);

Similarly, to add days or hours to date we can do as:

$subtractedTimeStr = strtotime("+ $hours hours", $strTodayDate);
$subtractedTimeStr = strtotime("+ $days days", $strTodayDate);

Hope this helps someone.

Get changed field names from database using PHP & MySQL

Yesterday, i had a problem to get changed field value in mysql from database. MY problem was,lets say i have a field "user_name" in users table and have value "Sudhir" in it, after some updates the "user_name" field's value changed to "John", now i had to find such fields whose values has changed.
After some testing with the codes, i was able to get the field name and its changed value from database. So here's the code snippet:

//define an array of field names and values
$uniqId = "1"; // this can be the user id in database, whose values are changed
//array of field names and changed values, i.e. these fields contain values other than listed in this array
$fieldsArr = array(
"first_name" => $firstname,
"last_name" => $lastname,
"location" => $location,
"ip" => $ip
);
//call function to get list of changed fields in database
$changedFieldValueArr = getChangedFieldValue($uniqId, "user_details", $fieldsArr);

This is the function part. Connect to database, select database first.

function getChangedFieldValue($uniqId, $tableName, $fieldsArr) {
$changedValuesArr = array();
$sql = "SELECT id FROM ".$tableName;
$sql .=" WHERE ";
foreach($fieldsArr as $fieldName => $fieldValue) {
$subSql =$fieldName ." = "."'".$fieldValue."'";
$finalSql = $sql.$subSql;
$res = mysql_query($finalSql, $this->connection);
if(mysql_num_rows($res) < 1) {
$changedValuesArr[] = array("fieldname" => "'".$fieldName."'" , "changedFieldValue" => "'".$fieldValue."'");
}
unset($res);
unset($finalSql);
}
//resulting field names for changed values are added to array
return $changedValuesArr;
}

And thats it. I hope this can be of some help to someone like me. The code can be customized to a greater extent depending on the need.

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.

10 November, 2010

Regular expression examples in php

Regular expressions in php are a good way for validating against user inputs. Though
usage of regular expressions slow the execution, and are really slower as compared to
string functions, they can be quite fun to play with if known how to. Regex can be used in different programming languages but since i work with PHP, i use them using PHP.

At the beginning, regex seemed to be invincible to me, but as i got into details of
its usage and worked with test codes, i got more and more interested.
So here are some of the common validation examples that can be done using regular expressions in php.
Following mentioned are code for 5 simple regular expression examples for validation in php.

1: Regular expression to check for integer value excluding 0

$test = "123";
$result = 0;

$pattern = "(^([1-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

2: Regular expression to check for integer value including 0

$test = "1230";
$result = 0;
$pattern = "(^([0-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

3: Regular expression to check for integer value double or float, such as 1.23, 0.48, , 0.487 etc

$test = "123.23";
$result = 0;
$pattern = "^(([0-9]{1,9})(\\.)?)(([0-9]{0,1})([0-9]{0,1})(([0-9]{0,1})([0-9]{0,1})?))$";
$result = (int) ereg($pattern, $test);
echo $result;

4: Regular expression to check for string between 1 to 255 characters, no spaces
 
$test = "thisisatest";
$result = 0;
$pattern = "^([[:alnum:]]){1,255}$";
$result = ( ereg($pattern, $test);
echo $result;

5: Regular expression to check for valid email address
 
$test = "this@gmail.com";
$result = 0;
$pattern = '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+' . '@' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$';
$result = (int) ereg($pattern, $test);
echo $result;

Above mentioned are just few examples that i have mentioned in this post. There is a long way to go with regular expressions in php. I hope this post provide at least some info regarding usage of regular expressions with php.

09 November, 2010

How to expire a link using php

Once i got a problem of how to expire a link after it is clicked once using php. My situation was,
i had to send some confirmation link email to users, and when a user clicked the confirm link then
it should be set as expired, i mean, clicking on it for second time (more than once) should not
execute a function, i.e it should act as a dead link when clicked once.
So for this problem, i used hash trchnique of php.
Here is what i did to expire link that is clicked once.
Step 1:
I created a hash using some secret and email address of user, as:

$secret = "234234456jbkjkbkj2b34kj2b4";
//the secret can be defined somewhere in the file or same function
$emailAdd = "john@doe.com";
//create a hash from this
$ourhash = sha1($secret.$emailAdd);
//store this hash in database

This created a unique hash, since email addresses are unique
Step 2:
Add the hash that we created in Step 1 to the confirm link,
that is to be sent to email, as,

$emailBody = 'This is a test.......';
$emailBody = 'Please click Confirm to proceed..!';

Now the hash is appened to the confirm link in email message.
Strp 3:
In somefunction.php file, check the hash in the link with ours,
since we know the email address and hash, we can do as,

//get the stored hash for $userId from database
$ourHash = $hashFromDb;
//now check this with the hash in url
$hashFromUrl = $_GET["hash"];
if($ourHash == $hashFromUrl) {
//update database or do some actions here
//delete the hash
}
else {
echo "This link in not valid.";
}

And thats it. I have done this in my own way, this has to be cleaned and securified
more, i think. But i hope this helps someone like me to startup.

08 November, 2010

Check if email is opened using php

Yesterday i had a problem to check if email is opened by a user using php. After some google search,i came to know that, checking if our sent email is opened by a user can be done by some simple trick.
Though this idea might not be applicable for all the cases, but can be of some help. This can be helpful in tracking users for newsletter, campaigns, etc. So following is the code snippet to detect if email is opened using php.
Step 1:
insert a 1 pixel image in the body of email that you create, like

$emailBody = 'This is a test message.';
$emailBody .='';
$emailBody .='Please feel free to contact me..!';
....
.....
//send email using mail() function of php


Step 2:
Create the file take_action_open.php and add following code

//get the userid from url of image source
$userId = $_GET["userid"];
//add code to insert this user to database
//or do something with it.
//this user has opened the email that you have sent.

And thats it. You can track opened emails using this method. As i already
said this method may not be applicable for all cases, since images can be
disabled by some mail services as well. So need to find some other solution
in such cases. However, i think this code might be of some help to someone
like me.

Get path of a file in PHP

Once i have to get location of a file using a single line of code in php. Here's how i did it.

$filePath = substr($_SERVER["SCRIPT_FILENAME"], 0, strrpos($_SERVER["SCRIPT_FILENAME"], "/"));
echo $filePath; // this gives the full file path

Hope it helps someone.

01 November, 2010

CSV to Multi-Dimensional Array in PHP

Once i needed to convert a csv file contents to a multi-dimensional array in php. Converting a csv to a multi-dimensional array
can be done by reading the file by using php's fopen function and then looping through to insert data to the array.
Following is a code snippet that is used to get csv to multi-dimensional array in php.
My csv file was in the format "name" "email_address" without any column names.

$formattedArr = array();
$filename = "test.csv";
//csv format was
//name test@this.com
//tester tester@mail.com
//sudhir sudhirconscious@gmail.com
if (($handle = fopen($filename, "r")) !== FALSE) {
$key = 0; // Set the array key.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count = count($data); //get the total keys in row
//insert data to our array
for ($i=0; $i < $count; $i++) {
$formattedArr[$key][$i] = $data[$i];
}
$key++;
}
fclose($handle); //close file handle
}
//csv to multidimensional array in php
echo "
";
print_r($formattedArr);
echo "
";
And thats it.

Get elements by class name in javascript

At times, i need function to get all the elements using class name in javascript. But since such function does not exist as in javascript, so i thought of creating a similar function that can be used to get elements by class name.
Here is the code snippet:

function getElementByClassName(strClassName) {
var eleNames = new Array();
var totalFrms = document.forms.length;
for(var i = 0; i < totalFrms; i++) {
//alert(document.forms[i].elements.length);
var eleLen = document.forms[i].elements.length;
for(var j = 0; j < eleLen; j++) {
if(strClassName === document.forms[i].elements[j].className) {
eleNames.push(document.forms[i].elements[j]);
}
}
}
return eleNames;
/*
for(t = 0; t < eleNames.length; t++) {
alert(eleNames[t].type);
}
*/
}
getElementByClassName("user_text");
Thats is. Hope this helps someone.