Showing posts with label PHP Tips. Show all posts
Showing posts with label PHP Tips. Show all posts

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.

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

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.

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.

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 "
";

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 "
";

22 December, 2010

Dynamic functions in CodeIgniter Model

Using dynamic function can be of great ease at times. Since i was developing some project on codeIgniter, i thought of giving it a try to create dynamic functions in codeigniter model. The following code is just a startup, if this works out good then will add more of the functions in it.
Functions can be created on the fly using PHP's magic method __call(). As per php.net this method is triggered when invoking methods that are not accessible in object context.
So, in codeIgniter as there are controllers, views and models. I thought of adding a model that would create dynamic functions, which can then be accessed by controllers.
The code snippet is just a test.
I created a Test_model.php file as:

class Test_model extends Model {
private $id = 0;
private $table;
private $fields = array();
function Test_model() {
parent::Model();
}
//setup the tablename and field names
function set_up_table($table, $fields) {
$this->table = $table;
foreach($fields as $key) {
$this->fields[$key] = null;
}
}
//magic method to set and get
function __call($method, $args) {
if(preg_match("/set_(.*)/", $method, $exists)) {
if(array_key_exists($exists[1], $this->fields)) {
$this->fields[$exists[1]] = $args[0];
return true;
}
}
else if(preg_match("/get_(.*)/", $method, $exists)) {
if(array_key_exists($exists[1], $this->fields)) {
return $this->fields[$exists[1]];
}
}
return false;
}
//function to insert to database
function insert() {
$this->db->insert($this->table, $this->fields);
return $this->db->insert_id();
}

}

Now the controller part:

class Welcome extends Controller {

function Welcome() {
parent::Controller();
}

function index() {
//name of fields in book table
$fieldsArr = array( 'id', 'author','title', 'publisher' );
$tableName = "book";

$this->load->model("Test_model", "test");
$this->test->set_up_table($tableName, $fieldsArr);
$this->test->set_author("John Doe");
$this->test->set_title("Advanced PHP Web Development");
$this->test->set_publisher("Wrox");
$bookId = $this->test->insert();

$this->load->view('welcome_message');
}
}

And thats it. The code in controller sets values for all the fields and then we call insert function created in our model. The main objective behind the code is to show how dynamic functions tend to ease out the process of coding.

16 December, 2010

Detect Ajax request using PHP

Sometimes, we need to detect ajax request using php. In such case, we can write following code that checks whether the request is ajax or not. It is helpful in conditions such as when i have to load a page depending on condition using a same function in php.

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
echo "Ajax request";
}
else {
echo "Normal Page Load";
}

And thats it.

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.

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.