Junal on the run

Archive for the ‘PHP’ Category

Before start with Facebook connect lets be familiar with 2 things that are essential to use Facebook Connect APIs.

What is Facebook Connect?

Facebook Connect is the next evolution of Facebook Platform — enabling you to integrate the power of Facebook Platform into your own site.

With Facebook Connect, you can enable your users to:

  • Seamlessly “connect” their Facebook account and information with your site
  • Connect and find their friends who also use your site
  • Share information and actions on your site with their friends on Facebook [from facebook wiki]

What is XFBML ?

Facebook uses XFBML as a way for you to incorporate FBML into your HTML. To see the all supported XFBML tags, please have a look here.

Now, I would like to use Facebook PHP client library to get my all friends in my site !

First of all, lets install an application to get the API key. In my case I named it as “fbconnect-test“. So we got an API and a SECRET key to bring Facebook in my site 🙂

it will be much easier to download given examples source code by facebook developers here. Lets open one HTML file (it could be demo1.htm) then renamed it as demo1.php

now, put your API key here ..

<script type=”text/javascript”>

FB_RequireFeatures([“XFBML”], function()

{

FB.Facebook.init(“YOUR_API_KEY”, “xd_receiver.htm”);

});

</script>

up the file(s) in your server and then run it. You suppose to see a log in button if you used the source code.

Facebook Connect Button

Facebook Connect Button

If you are not logged in Facebook then a log in prompt will appear so that you can insert your log in information. In my case it looks like the following…

Log in form

Log in form

ok once im logged in, I can access my friends list and show them in my site ! So let’s do that for time being …..

we have got API and SECRET KEY right ….

lets up the Facebook PHP client library in the server and then call friends list API to show them in our site..

include_once(‘facebook.php’);

$api_key = ‘API_KEY’;

$secret_key = ‘SECRET_KEY’;

$facebook = new Facebook($api_key, $secret_key);

$array=$facebook->api_client->friends_get();

this $array supposed to return our friends list…lets show our friends picture in our site from the array….

in my case i’m just showing 20 friends …

$count =0;

foreach ($array as $id)

{

$count++;

?>

<div class=”img”>

<fb:profile-pic uid='<?=$id?>’ linked=’true’ size=’square’/>

</div>

<?php

if($count==20)

break;

}

and I have used a simple css class to show thumb image nicely …

.img {

float: left;

padding : 20px 5px 5px 10px;

width:50px;

overflow: visible;

}

have a look at the output ….

Showing 20 friends from my friends list

Showing 20 friends from my friends list

for more please have a look at the following links ……..

http://wiki.developers.facebook.com/index.php/Trying_Out_Facebook_Connect

http://wiki.developers.facebook.com/index.php/XFBML

http://wiki.developers.facebook.com/index.php/Facebook_Connect

To check if an image/file URL exist, first thing came in my mind was file_exist() function. Thought it would be the best way to find whether my parameter that is throwing an image url is right or wrong. So I had to set a default image if there was no image found from the given link. file_exist() has a problem that it reads the directory of the file/image so when i’m reading an URL it will always return false. Well, I could separate the directory from the URL but it would be lengthy and messy, so I was searching for a better way. After reading the PHP manual online version I have found that this task can be done by getimagesize(). It returns an Array() with 7 elements. So idea is simple, if I get an array from the given URL then I can say that image is found otherwise not!

An example could be like this:

$url=getimagesize(“http://www.flickr.com/photos/27505599@N07/2564389539/&#8221;);

if(!is_array($url))

{

$default_image =”…/directoryFolder/junal.jpg”;

}

Sometimes strange things happen. I write some code and it’s not working. Strange errors! Well, certainly I have done something wrong – otherwise why it would generate wrong code in live site when it works fine in the local site?

I was trying to upload files from facebook. In other way, I had to allow users to upload their own files in facebook. First, I tried file uploading from local server and after uploading a file my $_FILE array would generate an array like bellow:

Array

(

[uploadedfile] => Array

(

[name] => Junal.jpg

[type] => image/jpeg

[tmp_name] => D:\wamp\tmp\php7.tmp

[error] => 0

[size] => 34693

)

)

But as soon as I moved these codes to live site my $_FILE array didn’t work and it was returning me an empty array! Strange! Form method was “Post” and I submitted a picture! What is wrong with it? I kept trying and trying…..

After trying several times I realized that my code was all right and then I moved to facebook WIKI and found this solution bellow:

http://wiki.developers.facebook.com/index.php/Files_Easy_Uploads

So it gives you a link where user can store their files and later this file can be called from your callback URL, I got a relief once I found it. It worked for me well. I had to sign in as a user and it returned me an array of file links and stuff to my callback URL.

After clicking on the link, it brings you this log in page and you upload your files.

I got all necessary link from my $_GET array. Later, all I had to do is, putting these all links in a database table. And that’s it rest of the things same.

To see an example code of this file uploading you can visit here: http://enabled.box.net/fb/simpleupload.phps

So why Facebook would not allow users to upload their files on their own way ? uhm, I guess its because they want to make sure right file is uploading and no copyright files being uploaded.

Is there any other way we can upload files in facebook? I’m very much interested to know about it. please let me know.

Recently, I have studied three types of PHP functions and they are: String functions, Date functions and Array functions. I have noted down some functions that were interesting. Well, PHP got thousands of built in functionality and I guess this is what makes PHP great. So, let’s have a look at some interesting functions from my collection.

String functions:

strpbrk ()

–          Search a string for any of a set of characters

Example :

$text = ‘Junal is studying php functions’;

echo strpbrk($text, ‘s’);
What will be the output? Well its will output: “studying php function”, because‘s’ is matched first.

strrev()

–          This will reverse the given string

Example:

echo strrev(“junal likes to be lost”);

output : “tsol eb ot sekil lanuj” – funny eh ?

strtok()

–          Tokenizing a string

–          Example :

$string = “Junal is being tokenized”;

$tok = strtok($string, ” \n\t”);

while ($tok !== false) {

echo “Word=$tok<br />”;

$tok = strtok(” \n\t”);

}

Output :

Word=Junal
Word=is
Word=being
Word=tokenized

ucfirst()

–          Ahh ! This is one of the most interesting and needy one that I used currently one of out facebook application, it uppercase the first letter of first word!

Example:

$string = ‘junal rahman’;

echo ucfirst($string);

output : “Junal rahman”

ok this above function make first letter of first word uppercase right. How about if we want all word’s first letter to be uppercase? Simple! We just have to use ucwords() function !

Date Functions:

Well, among all date functions I found one date function interesting 🙂

idate()

–          Format a local time/date as integer

Example:

$timestamp = strtotime(‘9th February 2008’);

echo idate(‘m’, $timestamp);

Output: “2”

Array Functions

Array_diff()

–          Computes the difference of arrays.

–          Example :

$array1 = array(“a” => “junal”, “anupom”, “manzil”, “ahsan”);

$array2 = array(“b” => “junal”, “anupom”, “manzil”);

$result = array_diff($array1, $array2);

print_r($result);

output : “ahsan”

array_key_exists ()

–          Checks if the given key or index exists in the array

array_multisort ()

I used this function in several occasions. Very handy function to sort the multiple arrays. It does a lot of help when we want to sort an array by rank/number.

array_product()

–          Calculate the product of values in an array

Example:

$a = array (2, 4, 6, 8);

echo $a;

output :” 384″

natcasesort ()

–           Sort an array using a case insensitive “natural order” algorithm

range ()

–          Create an array containing a range of elements

Well that’s all! After studying these array functions, I have found another interesting thing about ArrayObject.

$array = array(‘1’ => ‘one’,

‘2’ => ‘two’,

‘3’ => ‘three’);

$arrayobject = new ArrayObject($array);

Excellent stuff! By the way, I have to go now. There are thousands thing I don’t know about PHP. Have to get idea about them, have to run ….

Reference : PHP manual.

Mr. Duane Moraes is a Marketing Account Executive of Packt publications who emailed me like 2 weeks ago asked me if I was interested to review 2 PHP books. Well, I was glad to receive that email from him and I emailed him back saying that I would love to review them. These 2 books are:

  1. CodeIgniter for Rapid PHP Application Development and
  2. PHP Web 2.0 Mashup Projects

CodeIgniter for Rapid PHP Application Development   PHP Web 2.0 Mashup Projects

I’m so happy that today, I have received them! So, I’m gonna start reviewing these 2 books. I will start with “CodeIgniter for Rapid PHP Application Development” and of course I will let all of you know about this book. I’m pretty sure I’m gonna enjoy these books because i love PHP and CI is one my favorite PHP framework.

Well, I would like to thanks Mr. Duane for considering me as a reviewer of these book.

There are tons of PHP tutorials in the web. But a good tutorial depends on how easily it’s written and of course example is very vital to make a tutorial better. I have just read this tutorial from here, which are actually written for beginners. This tutorial that I’m talking about has three parts. I’m pretty sure if a beginner just read it carefully and practices, it will be really help him/her to understand what PHP and how it actually works. Well, this tutorial will give a good idea about php Framework concept as well.

First part: it starts from the very beginning. It includes database design and describes how to create some basic functions for the application.

Second part: you will see how to create a dynamic menu using php. I did the same thing with CakePHP for my garments ERP project. So, second part will give you some idea about framework concept.

Third part: it says about how to handle multiple items. So you will get a concept of foreach, for and while loop concept.

My requests, if you read these tutorials then please start from the first part. And of course if you run the code in your localhost you will understand it more.

Both of these PHP Frameworks follow model-view-controller architecture. This is why both of them got lots of things in common but at the same time they have some dissimilarity too. I was thinking to make a list of all those similarities and dissimilarities with some small examples so that when I move one framework to another, it can remind me the dissimilarities. I have pointed out some main features of these 2 frameworks to discuss about.

Installation: well, both of them got similar installment process. Like CodeIgniter installation in 4 steps.

  1. Unzip the package.
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.

This installation process is same for Cake “development setup”. But we don’t have to setup any URL for Cake.

Dissimilarities come when we want to increase security hiding our location. CI’s system folder can be renamed into something private. But in this case $system_folder variable name has to be changed from inex.php file into chosen name of the folder. CakePHP has 2 more installation process, these are: using a development setup, which allows us to easily view many CakePHP applications under a single domain, or using the production setup, which allows for a single CakePHP application on the domain.

Although both of their installations are very easy but comparing these two, I guess CI’s installation process is easier.

Scaffolding: I wrote a blog on Cake Scaffolding and CodieIgniter Scaffolding. I’m gonna say the same thing here, so let me just paste it here:

In cake Once you add this variable called $scaffold in your controller it gives an idea about early parts of development of your application.

Example: <?php

class YourController extends AppController

{

var $scaffold;

}

?>

But what if you forget to take it off before you up the project in real server and somebody guesses your URL? Well certainly scaffolding has edit and delete option right. So it’s not secured I guess.

I like how CodeIgniter is dealing with scaffolding. Almost same but there is an option for you to set secured scaffolding. You have a secret word option which will be set here:

application/config/routes.php in CI like this

$route [‘scaffolding_trigger’] = ‘ sewt ‘; //assume your secret word is “sewt”

So now use your scaffolding in the controller

<?php
class YourController extends Controller {

function Test()
{
parent::Controller();

$this->load->scaffolding(‘table_name’);
}
}
?>

To see this scaffolding you have to follow this URL path:

http://www.your-site.com/index.php/YourController/sewt/.

Isn’t it better eh?

Default Layout: CakePHP uses default layout, the layout has two variables by default: title_for_layout and content_for_layout. Each action automatically links to a particular view which gets spat into place. This is simply great to use for many pages. Once default page is setup, boring stuff like adding header and footer again and again completely gone.

CodeIgniter doesn’t have any default layout! I feel this is bad side of CI that it doesn’t have any default layout like Cake. It’s like row php code where I have to include header, footer each and every time I create a new file. To help on it I guess this post is really helpful, have a look here: http://hasin.wordpress.com/2007/03/05/adding-yield-codeigniter/#comment-55979

Model: first of all, I would like to give an example of a CakePHP model.

<?php
class User extends AppModel
{
var $name = ‘User’;
var $hasOne = array(‘Profile’ =>
array(‘className’ => ‘Profile’,
‘conditions’ => ”,
‘order’ => ”,
‘dependent’ => true,
‘foreignKey’ => ‘user_id’
)
);
}
?>

Here, Variable name (‘User’) must start with Capital letter and table name must be plural (‘users’). This is a strict convention that Cake follows.

One of the most powerful features of CakePHP is the relational mapping provided by the model. In CakePHP, the links between tables are handled through associations. Associations are the glue between related logical units.

There are four types of associations in CakePHP:

1. hasOne

2. hasMany

3. belongsTo

4. hasAndBelongsToMany

When associations between models have been defined, Cake will automatically fetch models related to the model you are working with. For example, if a Post model is related to an Author model using a hasMany association, making a call to $this->Post->findAll() in a controller will fetch Post records, as well as all the Author records they are related to.

In codeIgniter there are no model associations. There is no strict naming convention. Although class name must be capitalized. Let see an example if CodeIgniter model:

class Blogmodel extends Model {

var $title = '';
var $content = '';
var $date = '';

function Blogmodel()
{
// Call the Model constructor
parent::Model();
}

function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}

}

So, query in CI is almost like writing SQL command. I feel this is better in a sense that my query is optimized here. It searches exactly what I need. In Model association concept I saw many unnecessary results that I didn’t ask for. But sometimes I feel I can call CodeIgniter as VC pattern framework, because I can do almost  the same work of model in Controller 🙂

Ok, that’s all for today ….if you have any complains/comments/suggestions please write it down. I’m coming up with more similarities and dissimilarities in my next post……

References:

http://codeigniter.com/user_guide/

http://manual.cakephp.org/


View Junal Rahman's profile on LinkedIn
Subscribe to me on FriendFeed

Follow Me on Twitter

Archives

My photos

Downtown, Ottawa

Dream

Jasper, AB

Jasper, AB

Banff, AB

Folkfest, Bangladesh Pavilion Saskatoon

Lovely Sky

Stunt bikers on summer festival, Saskatoon

More Photos

Blog Stats

  • 421,308 hits