Category: PHP

Installing PECL subversion extension for PHP in Ubuntu 7.10

I was trying to interact with my subversion repositories using PHP yesterday and I knew that PECL has a extension named “SVN” for PHP users. So I tried to install in in my machine by when I tried to install it with the following command it always failed saying “unable to locate svn_client.h

sudo pecl install -f svn

Then I googled for some time to find out which package actually and I found that it is a part of libsvn which I didnt install in my machine which has ubuntu 7.10. so I found the appropriate package using the following command and it obviously locate the appropriate lib to install, which is “libsvn-dev

sudo apt-cache search libsvn

After that I just installed it via the standard procedure “sudo apt-get install libsvn-dev” and then tried to install the pecl extension once again. And whoa!, it works.

Here’s a small snippet to find out the difference of a single file from the repository under two separate revisions. in the following example svn_diff function returns two streams. one of them contains the difference and another one contains the error block.


<?php
list($diff,$error) = svn_diff("http://orchidframework.googlecode.com/svn/trunk/app/config/configs.php",
52,
"http://orchidframework.googlecode.com/svn/trunk/app/config/configs.php",
61);
echo "<pre>";
fpassthru($diff);
?>

Easy, huh?

whoops! naked_women are being part of php frameworks – LOL!

i don’t know if anyone before me already noticed this funny and cheap trick that the developers of kohana framework (which is a fork of codeigniter) have integrated with their distribution. while surfing the code base, i’ve found a file name “Naked_Woman.php” as part of kohana, located under system/libraries.

The content of this file is funny as well.


<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Merry Christmas!
 *
 * I wonder if this will be picked up by Google and cause a massive number of
 * hits to just this file....
 *
 * @author     Kohana Team
 * @copyright  (c) 2007 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
class Naked_Woman_Core {
	public function __construct()
	{
		throw new Kohana_User_Exception
		(
			'cash::generate(), plz?',
			'There are no naked women or cash generators in Kohana. Sorry! ;)'
		);
	}
} // End Naked Woman

didn’t know naked womens are so influencing to even php frameworks! – lol

working with models in orchid

as promised, orchid comes with real flexibility which lets you design your application in less time. in orchid, there is a nice active record object which helps you to interact with your database very easily. beside that, you can also write your own model class to facilitate comples business logics and operations. in this installment, we will learn how to achieve maximum speed and benefit by using the builtin model library of orchid with a toppings of the active record library.

2.1 connecting to a database

the built in data access libraries in orchid will help you to connect to mysql, postgresql, mssqlserver and sqlite in a minute. beside that you can also connect to other database engines by using native wrapper of pdo. all you have to do is to add a few lines in the configuration file and whoa, you are connected. don’t you believe me? lets see

create a file named configs.php in app/config/configs.php with the following contents

$configs['db']['production']['dbname']="";
$configs['db']['production']['dbhost']="";
$configs['db']['production']['dbuser']="";
$configs['db']['production']['dbpwd']="";
$configs['db']['production']['persistent']="";
$configs['db']['production']['dbtype']="";

in orchid you can have as many database state (such as production, development or whatever) as you want. in the example above, we named our db state as “production”. rest of the code is self explanatory, right? the only confusion you might have is about “persistent”. well, if you set it to true, the connection to your database stay alive as long as you are using the same connection strings, which will save some microseconds from connecting every time your script executes.

you are not done yet. there are some more configuration directives we have to add. we haven’t yet specified the type of our database and which db state orchid will use, lets do that. add the following two lines in your configs.php


$configs['db']['usedb']=""; //true or false
$configs['db']['state']="development";

the value of “usedb” could be either one of “mysql”,”mysqli”,”pgsql”,”mssql”,”pdo” or “sqlite”. and using usedb you can tell orchid to use database engines or not. so you can save the connection parameters for use later by specifying the “usedb” parameter to “false”.

ding dong! you are connected to your favorite db engine in a minute, as said.

2.2 good coding and bad coding while working with database

in orchid (and in most other framework possibly) you can directly use the internal dbmanager to execute sql, fetch the result and manipulate that through out your application. i have seen developers manipulating records in controllers, in views and skipped the most appropriate part where these manipulation should take part in fact, models. many of you dont make use of the models in your application and write the business logic entirely in your controller, feeding the inner monster of your application to be the most vigorous unmanageable giant. dont blame php as a tool to write unmanageable code because this unmanageable code solely depends on you – you. always try to use models to encapsulate the business logic and separate it from your controller. lets model do it’s job.

2.3 working with models

in this section we will write a simple model and insert some data inside a table. here comes the schema of the table.


CREATE TABLE `comics` (
  `id` int(11) NOT NULL auto_increment,
  `comicname` varchar(255) default NULL,
  `comicurl` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
)

in orchid, you can instantly create a reference to any table in your database by auto model feature of orchid, which looks like the code below, which will reside in a controller.


$comicsmocdel = $this->model->comics;

orchid will dynmically create a reference of the “comics” table instantly, no more hassle for you. but there are significant causes why we will write models by coding it. the auto models support only the very basic data manipulation. if you want to encapsulate business logic inside, we definitely need to write the code inside. lets learn first how to work with a auto model like this one.

a model in orchid supports the following methods

  • selecting data
  • basic joining
  • insert
  • delete
  • update
  • finding based on criteria

as we have already created a model, lets make use of it. the following piece of code will insert a record in the comics table using the model.


$comicsmodel = $this->model->comics;
$comicsmodel->comicname = "Nancy and Sluggo";
$comicsmodel->comicurl = "http://comics.com/comics/nancy/index.html";
$comicsmodel->insert();

this is really simple to work with models in orchid, like as i said, the above example will insert a data in your data table named “comics”. now lets see how we can modify the existing data. in the following example we will change the name of the comic to the data which we’d just inserted.


//inside the controller action
$comicsmodel = $this->model->comics;
$data = $comicsmodel->find("comicname = 'Nancy and Sluggo'");
print_r($data);
if(!empty($data))
{
$comicsmodel->comicname="Nancy & Sluggo";
$comicsmodel->update();
}

the find method can take any clause and find records according to that. similarly as update and insert, you can delete records using models in orchid.

in upcoming tutorials we will learn more on models and encapsulating business logic by writing in by our own πŸ™‚

facebook data storage api can really be the replacement of memcache

why not! all you need is a fast-n-furious caching storage for your facebook application which stores values against a key, same like a hash table. facebook data storage api does the same for you. using the batch api in facebook rest client you can seriously think it as an alternative of memcache. there are many developers who cache the data using memcache. memcache is definitely the state of the art caching solution for those who can afford hosting their application in a dedicated or vps server and knows how to install and successfully manage it. it. in other hand, facebook’s data storage api is an excellent solution for those who really want to make use of this awesome development platform without minimum hassle. all you have to do is remember some api and thats it.

lets see how you can use the facebook data storage api.

1. create the object manually (not using api)
an object in data storage api stands for something like a table. it contains some properties (columns) and their values(field values) stored against a key (think about a primary id). using the application control panel you can easily create such an object.

a. visit http://www.facebook.com/developers/apps.php?ret=2
b. select your application and click the link “http://www.facebook.com/developers/dsadmin.php?app_id={your application id}”

from this page you can create an object and create the properties. lets consider that the object name is ‘comics’ and the properties are “comicname[string]” and “comicurl[text/blob]”.

2. insert data into this object
using the storage api you can insert data into this object against a hash value. for example, lets have a look at the following piece of code

<?php
//after initializing the app client
//set value to the properties in a batch process
$facebook_api_client->begin_batch();
$facebook_api_client->data_setHashValue("comics","nancy","Nancy And Sluggo","comicname");
$facebook_api_client->data_setHashValue("comics","nancy","http://url_of_this_comic","comicurl");
$facebook_api_client->end_batch();
?>

the example showed above will set the value of two properties in “comics” object against the common key “nancy”.

setting up the values to the properties of an object in a batch process will speed up your application execution time by running all the api calls in that batch at once. the same thing applies if you want to retrieve the values of those properties.

3. retrieve the values
now when you need to re use the value of that object in your facebook application, you can do it like this

<?php
//retrieve the values of two properties "comicname" and 'comicurl"
$facebook_api_client->begin_batch();
$comicname = $facebook_api_client->data_getHashValue("comics","nancy","comicname");
$comicurl = $facebook_api_client->data_getHashValue("comics","nancy","comicurl");
$facebook_api_client->end_batch();
?>

thats a tiny introduction to the storage api of facebook. there are lots more you can do by defining associations (much like table relations between two tables) and other available apis in this category. i will focus some of them in my upcoming blog posts.

before ending, revise the title of this blog post as “facebook data storage can really be the replacement of memcache for facebook application developers”.

getting started with orchid framework

today i was planning to start the documentation of orchid framework for the rest of us(?). so this one is the first installment of this series. you will find small tutorials everyday. just stick with the series and you will see how far we can fly you. time to get high πŸ™‚ [please note that the text in this series will be all-small cap]

getting started with orchid

orchid is a small framework with bare necessities to kick start developing killer php web applications. this framework is not flooded with unnecessary features and libraries. it only contains the essential helpers and libraries to boost up your development, not slowing it down. orchid features a very short learning curve, which will keep you trouble free. small footprint and excellent profile will be your first choice, which you will definitely realize once you start realizing the power that orchid brings in your hand. long story short, orchid is the next framework going to rock.

you can checkout orchid from it’s subversion repository
svn checkout http://orchidframework.googlecode.com/svn/trunk/ orchidframework

orchid comes pre equipped with excellent configuration directives in a config file, which we will focus in details in the upcoming tutorials. for now lets just start as is.

to create your first application, we need to create a folder named “app” inside the orchidframework directory. after you create that, there will be three directories named app, core and tests.

in orchid, controllers reside in app/controllers directory. views (templates) reside in app/views/controller_name/ directory, which means if the name of your controller is “blog”, all your views remains in app/views/blog/ directory. lets create our first controller named “talk”. the controller file will be app/controllers/talk.php.

a controller in orchid is a normal php class file which extends the base controller class. all the public methods in a controller class are considered as action. a method named “base” is the primary action for all the controller in orchid. and for now, this is all the information you need to create your first controller in orchid.

lets write a sample action in our controller, named “base”

<?php
/**
 * the source file is app/controllers/talk.php
 */
class talk extends controller
{
	public function base()
	{
		echo "hello";
	}
}
?>

now you can see this controller in action by pointing your browser to the following location. i’ve considered that you hosted orchid in your document root (i.e /var/www/orchid)

http://localhost/orchid/talk

whoops, what have we done wrong? why do we get an error?

we are seeing this error because we didnt write our view (or template, whatever you call it) yet. and this is not a good coding practice to output anthing directly from your controller. whatever the size of the output, you should display it by passing the data to a view first. this will ensure the consistency of your project through out the application. orchid is flexible, but keeping the word “flexibility with responsibility”

lets write the view file, named “<i>base.php</i>” which will reside in app/views/talk/ directory.

<?//the source file is app/views/talk/base.php?>
<?=$talkings;?>

so where from do we get the variable named $talkings? dont worry, you will have to pass it to the view from your controller. in fact through out your application you have to pass all the data to a view from the controller in almost every mvc framework and orchid is not the exception in this case. lets re write the controller

<?php
/**
 * the source file is app/controllers/talk.php
 */
class talk extends controller
{
	public function base()
	{
		$this->setViewParam("talkings","hello world");
	}
}
?>

now you will see the output “hello world” as output when you point your browser to http://localhost/orchid/talk

orchid is very flexible and if you need to raw output (for example after a ajax request) some content from your controller, you can even do that. orchid wont restrict you from not doing so, but what we really said is that for good coding you should follow this guideline.

so that’s it. getting started in orchid wont take more than 5 minutes and that is where the blessings of using a framework is in. in next tutorial we will learn how to use a model in orchid.

WorldTimeEngine – How about making your own in PHP?

I recently came by this site WorldTimeEngine where users can search the local time of any place using the name, street address or just latitude and longitude. Since that time I was thinking how easily you can make your own. As long there are some good people over there (For Geocoding API) – its a not a big deal, you know? Lets have a look at the following PHP code.


<?
$place = "Bucharest";

$geodata = getGeoCode($place);
print_r($geodata);
echo getTime($geodata['lat'],$geodata['lng']);

function getTime($lat, $lng)
{
$url = "http://ws.geonames.org/timezone?lat={$lat}&lng={$lng}";
$timedata = file_get_contents($url);
$sxml = simplexml_load_string($timedata);
return $sxml->timezone->time;
}
function getGeoCode($address)
{
$_url = 'http://api.local.yahoo.com/MapsService/V1/geocode';
$_url .= sprintf('?appid=%s&location=%s',"orchid_geocode",rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
preg_match('!<Latitude>(.*)</Latitude><Longitude>(.*)</Longitude>!U', $_result, $_match);
$lng = $_match[2];
$lat = $_match[1];
return array("lat"=>$lat,"lng"=>$lng,"address"=>$address);
}
else
return false;
}
?>

Changing the variable “$place” to “Bucharest”,”Dhaka”, “Toronto” and “Oslo” gives me the following result


Array
(
[lat] => 44.434200
[lng] => 26.102955
[address] => Bucharest
)
2008-03-01 08:41

Array
(
[lat] => 23.709801
[lng] => 90.407112
[address] => Dhaka
)
2008-03-01 12:42

Array
(
[lat] => 43.648565
[lng] => -79.385329
[address] => Toronto
)
2008-03-01 01:42

Array
(
[lat] => 59.912280
[lng] => 10.749980
[address] => Oslo
)
2008-03-01 07:43

Nice, Huh?

Unexpected return value from Facebook FQL.query via PHP REST Lib

While working with FQL I suddenly found a bug in one of our applications. The method which we used to count number of friends of a specific user who has added that application was returning 1 when there is no friend actually installed itΰ₯€ Using the following FQL you can easily find that. (FQL doesn’t support “count” – so you cant use it)

SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {$userid})

The PHP code may look like the following one

function getTotalFriends($userid)
{
global $facebook, $mysql;
$Users = $facebook->api_client->fql_query("SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {$userid})");
$NumberOfUsers = count(trim($Users));
return $NumberOfUsers;
}

So what would you expect when there is no friend who has added this application? Definitely the FQL query should return an empty array. So that counting elements of that array tells you that you have “0” friends. But actually it returns a white space. What’s the difference between an empty array and a white space? l

count(array()) returns 0
count (” “) returns 1

So even when you dont have any friends, your method actually returns you “1”. The return result is not expected. What does your common sense says? Either the method should return false or an empty array. Not a white space.

Here’s the correction


function getTotalFriends($userid)
{
global $facebook, $mysql;
$Users = $facebook->api_client->fql_query("SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {$userid})");
$NumberOfUsers = is_array($Users)?count($Users):0;
return $NumberOfUsers;
}

Hacking SlideShare.net using PHP

Duh! you really believed that tricky title? come on!

But hey, wait. Here’s something I’ve found for you!

I am a big fan of slideshare becoz of their fantastic presentation sharing service and also the display. but it also hurts me when I can’t download some of these awesome slides available there for my offline reading. So I just spent some time today analyzing the HTTP requests made by the player available in slideshare using LiveHTTPHeader extension and found a way to download any presentation you want! There are many slides available in slideshare where you see that “Download not available” – But as long you have some knowledge on web-scrapping, that doesn’t matter at all.

Look at the following PHP code which gives you a list of URLs of the slides from any slideshow in slideshare.net – whether the presentation is available to download or not! for example the presentation on “Ajax and PHP” by John Coggeshall is not available to download. The url is of that presentation is http://www.slideshare.net/coogle/ajax-and-php


<?php
$slideshowUrl="http://www.slideshare.net/coogle/ajax-and-php";
$slideshowPageContent = file_get_contents($slideshowUrl);
$pattern = "~doc=([\w-]+)~";
preg_match($pattern,$slideshowPageContent,$matches);
$xmlurl = "http://s3.amazonaws.com/slideshare/{$matches[1]}.xml";


$sxml = simplexml_load_file($xmlurl);

foreach ($sxml->Slide as $slide)
echo $slide['Src']."<br />";
?>

The output will be something like this

https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-1.swf
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-2.swf
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-3.swf
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-4.swf
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-5.swf
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-6.swf
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-7.swf
..........
https://s3.amazonaws.com:443/slideshare/ajax-and-php-1194421981517706-1-slide-40.swf

I am sure you are going to love me! πŸ˜€

Installing Imagick extension for PHP in Ubuntu 7.10

I already have ImageMagick installed in my machine and I tried to install the Imagick extension for PHP but I was stuck with strange errors. I have spent couple of hours today to figure out what I did wrong and Why I cant build that extension. Finally I’ve figured out that I must install ImageMagick from source first to build that extension. Heres how to

1. You have to install ImageMagick from source and Its a Must. Otherwise the extension for PHP wont compile. It will show you a strange error like magic_wand.h not found.

wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz
tar zxf ImageMagick.tar.gz
cd ImageMagick-6.3.8
./configure
sudo make
sudo make install

2. Now download the Imagick extension source from pecl.php.net – I tried imagick-2.1.0RC3

wget http://pecl.php.net/get/imagick-2.1.0RC3.tgz
tar zxf imagick-2.1.0RC3.tgz
cd imagick-2.1.0RC3
phpize && ./configure
sudo make
sudo make install

This will make compile imagick source and build imagick.so – In my machine, I found imagick.so in the following directory

/usr/lib/php5/20060613+lfs

3. Now add “extension=imagick.so” in your php.ini (You may need to write the full path of imagick.so based on your configuration)

4. Restart your web server and thats it

Look at the php ini – you will see something like below (Click to enlarge)

Imagick