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

30 December, 2010

Basic url rewrite example

URL that is readable looks nice. But despite efforts by developers, sometimes for instance, using a Content Management System (CMS) serve url's in the format like,

http://www.testthis.com/list_products?cat_name=Shirts&cat_id=8


Now, this is really a bad url, and is prevelant with dynamic pages. Some of the problems of such url's are:
1) It exposes the type of data, query string to malicious users.
2) The characters such as question mark and ampersand can be troublesome.
3) Such url's wont be indedxed by search engines.

Solution to this is, above url can be mapped to something like this;

http://www.testthis.com/products/Shirts/8


Looks much better. And in order to do such mapping, we need url rewriting.
Apache's mod_rewrite gives us the ability to rewrite urls. Url rewrite can be
done to redirect from old to new address, clean up dirty url's, as mentioned above.
This makes our url's search engine friendly which means search engines can index such urls.

For url rewrite, we create a file .htaccess at the root of our project, and add following line.

RewriteEngine On


Basic Redirects

Lets say we moved all of our files from an older location to a new one, now we want to redirect all the links to current location. For that we can do the following.

RewriteEngine On
RewriteRule ^old\.html$ new.html


What the above rule does, is, it simple redirect from old.html to new.html page.
The ^ sign indicates Start of the url to be matched. If this character is removed, then our rule would also match hold.html
The $ sign indicates end of the string to be matched. In this case users would not know a redirect has occured from old.html to new.html

But lets say you want users to know that redirect has occured, that means you want to force a redirect. In such case you can do as,

RewriteEngine On
RewriteRule ^old\.html$ new.html [R]


Using Regular Expressions in Url Rewrite
The full strength of mod_rewrite can be felt at expense of complexity. Using regular expressions for url rewrite, you can have rules for set or urls, and have redirection for all to actual pages.
For example,

http://www.testthis.com/list_book?bookId=20


Now, we can rewrite this kind or url to make it friendly, as,

RewriteEngine On
RewriteRule ^book/([0-9][0-9])/$ list_book.php?bookId=$1


So above rule will create urls such as, http://www.testthis.com/book/8

But if a user types in like, http://www.testthis.com/book/8, our url rewrite rule wont work, as the slash at the end is missing, so to prevent such problems, we can do as,

RewriteEngine On
RewriteRule ^book/([0-9][0-9])/$ book/$1/ [R]
RewriteRule ^book/([0-9][0-9])/$ list_book.php?bookId=$1


Now, if a user enters something like book/12, our first rules comes in to add a slash at the end,then second
rule comes into play.

Regular expressions in url rewrite can be expanded by using modifiers, that allow you to match url with indefinite number of characters. Lets say, our url is like,
http://www.testthis.com/list_book?bookId=220

Our rule wont match this, as we have checked against two digits only, so we should use modifiers in this case.

RewriteEngine On
RewriteRule ^book/([0-9]+)$ book/$1/ [R]

+ indicates one or more of the preceeding characters or range.
* means 0 or more preceeding characters or range

So, above rule will match both book/1 and book/3000

In this way we can use mod_rewrite to rewrite url. These are just an introductory examples. There's a lot more way to move ahead in url rewriting and regular expressions. I hope this basic url rewrite post can be of some help to others.

27 December, 2010

Excel to Array in PHP

Customer's data can come from various sources, and making it easier for them to get the data into our system means we are increasing our customer's count. So, our code should support importing of data from different sources.
And one of the common sources can be Excel. So, we need to create an interface for customers so that they can load data from excel to our database.
Instead of spending hours entering data into forms, users can simply use tools such as excel to load data from excel using php.
In the following code, we load data from excel in php, read it and display the data back to the users. The displaying of data part can be replaced by inserting the loaded excel data to database to suit individual needs. And we are
using XML to do this.


Let's say we have a form "form.php" as:


File:





Now after user adds an excel file and uploads it, following code "do_act.php" is executed,

$dataArr = array();
if($_FILES["excelFle"]["tmp_name"]) {
$xmlDom = DOMDocument::load($_FILES["excelFle"]["tmp_name"]);
$allRows = $xmlDom->getElementsByTagName('Row');
//loop through each of the row element
foreach($allRows as $row) {
$cells = $row->getElementsByTagName('Cell');
$rowData = array();
foreach($cells as $cell) {
$rowData []= $cell->nodeValue;
}
$dataArr []= $rowData;
}
}

//so now you can check for the array of data as:
echo "
";
print_r($dataArr);
echo "
";