Archive for the ‘Php Talk’ Category.

Working with SMF

I was working upon upgradate & modification of a forum powered by SMF. My first job was to upgrade the forum from SMF 1.1.14 to SMF 2.0.1. I found no difficulties in doing the upgardate. If you are not well accomplish with SMF upgrade process then here is a good instruction for you.

My next job was to customize the board icons. I googled a mod for this purpose. It is cbi v0.5 (Custom Board Icons). I downloaded the latest version of the mod which is I tried to follow the installation process for the mod but got no result. Then I tried for the manual installation instruction for SMF version 2.0.1. But it was my bad luck as I found the modification wasn’t compatible with version 2.0.1. So I had to spent some time with the code to make it work. This is what I had done.
Continue reading ‘Working with SMF’ »

Indian currency number 2 word conversion

I had created number to word conversion function earlier. Now while working upon a web based financial management application I need to use this function once more. However I found my old function is not working properly with big numbers and also with currency amount(2 digit decimal value). So I need to change the code a little bit. Ranajit suggested me to put this a post as he didn’t find out any such good conversion code. He informed me about some PEAR class [Numbers_Words], but it provides USD as currency.

First check this working example here – CurrencyToWords, then the code is here:-
Continue reading ‘Indian currency number 2 word conversion’ »

Auto increment Value of a MySql table in PHP

In MySql database the auto increment value of a field is a very important feature that we use frequently for our projects. Value of a auto increment field is a auto generated number. This number generates when you insert a row in the table. Most of the cases we make data type of that field as integer and as primary key. In many of my projects I have used this field value as the primary ID and mapped other data stored in other tables.

In PHP a new value of this type of field can be accessed after inserting a record in the table, using the function mysql_insert_id(). But you can many such cases where you need to access this value before inserting the record. Earlier I used a technique to get that value. Execute a simple sql query to get that value. The sql is:

  1. SELECT MAX(prodId) FROM ProductTable

Where prodId is the field name with auto increment and is the ProductTable table name. Now add 1 with returned value and you will get the new value for that field. However this process may produce incorrect result if you do delete operation upon that table. Let me explain a little more.

Say currently the ProductTable contains 100 records. So the possible next record Id will be 101. Now if you delete record no. 21 or 49 or 65 or 78 you will still have the next record Id as 101. But say if you delete record 100. Logically you should get the next record Id as 100. Your sql query will give the value as 99 and adding 1 with it will produce 100. Seem no problem, right? Wrong, just insert a record and you will find the prodId for the record is 101. How this happened? MySql database stores 1 as starting value when you create the table. Now every time you insert a record the auto increment value get incremented by 1.This way it produces a unique number every time you insert a record in the table. Generally table in MySql database don’t reuse the deleted Id. As a result the above said process will not work in case deletion of record.

Continue reading ‘Auto increment Value of a MySql table in PHP’ »

SEO Correction in PEAR::Pager

Pagination is a common practice to show big volume of data. It is quite important if you are showing dynamically populated data.

For myself I mostly use PEAR::Pager to display paginated data. If you are familiar with this package then you know that you can use 2 types of pagination display, as – sliding and jumping. In case of sliding display with a common practice is to use it with constructor option append:true and urlVar:<variablename>.

Let me show an example of this kind of usage –

  1. $Params = array(
  2.           ‘itemData’ => $dataDetails,
  3.           ‘perPage’ => $ViewPerPage,
  4.           ‘append’ => true,
  5.           ‘separator’ => ‘|’,
  6.           ‘spacesBeforeSeparator’ => 1,
  7.           ‘spacesAfterSeparator’ => 1,
  8.           ‘clearIfVoid’ => false,
  9.           ‘urlVar’ => ‘page’,
  10.           ‘useSessions’ => true,
  11.           ‘closeSession’ => true,
  12.           ‘mode’  => ‘Sliding’,
  13.           ‘importQuery’ => true,
  14.           ‘linkClass’ => ‘LinkStyle’,
  15.           );
  16. $Pager = Pager::factory($Params);
  17. $DataDetailsInArray = $Pager->getPageData();
  18. $PaginationLinks = $Pager->getLinks();

Now if you print/echo the $PaginationLinks, then you will get pagination like 1 2 3 4 etc.

Now let me describe you the problem:
Say your page url is mydata.php. So mydata.php page will show the first page of paginated data. while using the pagination links you will get a page with url mydata.php?page=1. This page shows the first page of paginated data. Now you are having a page with 2 different url like mydata.php and mydata.php?page=1. In SEO this is known as duplicate content. This is not good if you are seriously deal with SEO.

Here is the correction for this. This is simple but effective.

  1. if(isset($_GET[‘page’]) && $_GET[‘page’] > 1)
  2. {
  3.    $PaginationLinks[‘all’] = str_replace(array(‘?page=1"’, ‘&amp;page=1"’), ‘"’, $PaginationLinks[‘all’]);
  4. }

Use this code section just after generating $PaginationLinks. Hope this will help you. As always comments/suggestions are welcome. But spammers please don’t waste your time. :)

Freetag PEAR DB Version

While working with tagging application my favourite is freetag by Gordon Luk. It is a comprehensive open source tagging and folksonomy code in php. The source code is also hosted in Google Code. The best feature of it is you can use this code with little modification to fit your requirement. First time I used it in for their book store application. Currently I am using it in another website which is under development.

I am having an issue of compatibility with this code and I am writting this post for it. If you look at the code you will find that it uses the ADODB Library for database operations. In my case I am happy with PEAR::DB. Now for me to use this code I need to use 2 different database component as PEAR::DB and ADODB Library. It seems useless to me. So I decided to make the code compatiable with PEAR::DB. While working upon the compatibility modification I also made 3 changes as

  1. I have written a function as show_debug_text() which is a replacement of debug_text().
  2. I have removed the silly_list() function from my code as it was declared as deprecated.
  3. I have renamed the main class file from freetag.class.php to freetag.db.class.php

Here is the sample code for use this

  1. <php?
  2. require_once("/path-to/freetag.db.class.php");
  3. $DbObj = DB::connect($dsn, $options); //this is the database connection object using PEAR::DB
  4. $OptionArray = array(
  5.                ‘table_prefix’ => ‘mytags’,
  6.                );
  7. $TagObj = new freetag($DbObj, $OptionArray);
  8. // Use this object to call tag related functions .
  9. ?>

Here is the code modified by me.
If you use this code please let me know if you have any problem.

PHP serialization or Json

Information storage and retrieval is an important job while designing or developing an application. We all know how to store data with normal data types in database or file systems. Here I am going to discuss about storage and retrieval of data having complex type. Complex type means they are not like normal string or number or boolean values. Complex type means data structure or objects.

Think of a situation where you are working with some array. Now there may be some situations where you need to store the array and retrieve it back. If you are familiar with OOPS concept then objects are another type which you may need to store and retrieve.

Serialization is the process by which you can convert an object or data structure into a sequence of bits which can stored and retrieve back. Serialization is also known as deflating or marshalling. The opposite process (converting the serialized sequence of bits to object or data structure) is known as Deserialization or inflating or unmarshalling. Most of the important languages have their own implementation of these processes. In Java provides automatic serialization by implementing the interface. In perl there are modules like Storable or FreezeThaw. Python implements serialization through the standard library module pickle. In PHP there are two built-in functions as serialize() and unserialize() for this purpose. However as I will continue the discussion with PHP then you should be aware of the fact that – there is a difference in the implementation of serialization in PHP 4.x and PHP 5.x.

Continue reading ‘PHP serialization or Json’ »

QuickForm and AutoSuggest

The best example of auttosuggest filed I can instantly think of is Google. While designing dynamic forms I felt the requirement of such field. As I mostly use PEAR class and HTML Quickform to design dynamic forms in php. However in HTML Quickform there is autocomplete type but still there is no support for autosuggest. I googled a lot to get such support, but found it out in RFC of HTML Quickform. So I started working upon it. My first job was to found out a autosuggest Javascript code suitable for integration. I searched out an autocomplete javascript code by Beau D. Scott

The reasons why I selected Beau’s code is :
The code is simple to use but robust and has good documentation.
It uses standard JS library like prototype and scriptaculous.

Now having previous knowledge of integration of QuickForm and Jscalender I created the code for autosuggest class. This autosuggest class file contains constructor function, toHtml function which generates the HTML code for the field, getFrozenHtml function to return the autosuggest content in HTML and finally the registering process of the autosuggest type with HTML QuickForm. I put this autosuggest class name as autosuggestwce. View this wceautosuggest.php file.

To use this autosuggest field in HTML Quickform you need to have 3 javascript files as prototype.js, scriptaculous.js and autocomplete.js. Prototype Javascript is used for javascript framework, Scriptaculous for show and hide effect and AutoComplete is the main javascript functionality file. Among them scriptaculous.js can be removed if you don’t like to show effects, but you need to modify certain section in the wceautosuggest.php file. You also need to declare $GLOBALS[‘_HTML_QUICKFORM_AUTOSUGGEST_BASEPATH’] the global path defining variable for the javascript files path in the page where you will generate the form.

This autosuggest uses php script to populate values. The name of the php script has to be mentioned in the $attribute array for the key ‘fileref’.

Continue reading ‘QuickForm and AutoSuggest’ »

Web site hacked via HTACCESS

Here is another example how your site got hacked. I found this instance very recently in Godaddy server. This type of site hacking is not very common. You may not be able to detect any specific web page infected if you search your site using Google Diagonestic tool for safe browsing mentioned in my earlier post – Iframe code injection. In this kind of attack none of your web pages get infected but your .htaccess file gets modified and becomes the main source of redirection to malware containing site. Let me show you an infected .htaccess file for example.


Modified HTACCESS file used for hacking

Experienced developer can understand why this is so dangerous. Let me explain a little for the newbies. In case of apache web server configuration directives are described in httpd.conf file. Many cases this file can’t be accessed or modified due to security reasons. So to change some configuration directives for a specific website or its sub directory best solution is to use .htaccess file. To know further about .htaccess file and its functionality you can read .htaccess files. However URL rewriting, URL redirection, authentication are the important functionality .htaccess file are used for.

In the example htaccess file there are 3 sections. First line is for instructing the apache web server to put the rewrite engine on. This is first section. Second section goes from line no. 2 to line no. 8. This section is basically for condition checking on URL. Its checking if the visitors are coming from a website or page with URL containing the following words like google, aol, msn, yahoo, yandex, rambler or ya. NC means pattern checking will be case insensitive. OR means combines with other rule. Third section is in line no. 9. It says if any of the above pattern checking become true then it will redirect to the specified URL. Here R means redirection. Normally this generates HTTP response code 302 means moved temporarily. L means this is the last rule.

So the result is that if some visitor coming to the site from above specified search engine, they will be simply redirected to the malware site without understanding whats happening. So be careful if you come to know your site gotta hacked and youre unable to find out why then take a look at your .htaccess file.

Iframe code injection

After a long days I am back for blog post. Last one month I was very much irritated with the problem occurred in some of my client website. In a Sunday morning while I was sleeping one of my client ranged me and asked me to check her website as she got a mail from google that her website is spreading malware. I got confused as I had never faced this kind of problem. I started checking the website. But the antivirus in my Laptop didn’t allowed me to open the site at all. Then I decided to go to my office to check the situation.

In my office I checked the site thoroughly(OMG, I was able to open the site in my office). I found iframe code with hidden visibility was inserted in some pages. To be more specific index pages. I checked all the index pages in office PC, deleted the infected pages in the server and uploaded the pages from PC. Checked, cleaned all the html, php, temporary files. Almost near about afternoon I was back to my home while thinking how this happened.

Iframe Injected

Iframe Injected

Next Morning after arriving in the office I started checking the website and I found it was again infected by the hidden iframe. Site url was different as earler it was .cn and next day it was .ru I was upset about how to fix the things. Believe me or not in the last one month this site got infected 27 times. Our team had experienced the same attack for 5 more site. It was a horrible experience for us.

We had done lot of googleing to find out the preventive measurement. We found out lots of information regarding this. Some of them are good and some of them are misleading too. So here I like to point out some effective ones only.

  1. You should have good antivirus installed in your system from where you access web. I am using avast free edition and it works fine for me.
  2. Please check your websites on a regular basis. If you see if any web page with a blank section in the top them be almost sure that it is infected. Your antivirus should give you warning.
  3. If you find any of your website get infected then start following the next steps.
  4. First of all scan your machine with the antivirus. A boot time scan is more preferable.
  5. Replace all the pages in the website using a local copy from your system. If the web site is too big to repalce then try to repalce all the pages with name index. Then check the site again.
  6. Once the site is cleaned change the ftp details for the site and if possible do the same for the other sites whose details are kept in your ftp application.
  7. Keep checking the site in a short span of interval.

You should also check your site in google too. If google find out some problem with your site they may have shown a warning message like “This site may harm your computer”. Another way to check your site is

Continue reading ‘Iframe code injection’ »

Picasa web album slideshow – Development guide

I was looking for a application to embed slideshow using pictures from picase web album. I found some plugins which can be used in blog or myspace. Some of them uses the picasa slide show url opened in a iframe or div. Then you will have less control on the slideshow as it is controlled by the slideshow application of picasa. But I required more control on the images from picasa.

I was looking for some application which will fetch/store all the images for an album in picasa and create a slideshow with more control on the images. I found nothing thats suites my requirement. So I started to design an application of such kind. On the basis of functionality I sub devided it into two major part. First is fetch the image related information for an album and store it if required. Second is display the slideshow using those image information.

In picasa you can view the pictures as set or individual but you won’t get actual picture name or its location. So I found now simple way to get the pictures name and their location. While searching more for such option I found there is a RSS feed for each album. The RSS feed provides image names and its location details. It makes my job easier. Now objective became to process the RSS feed to get the image related information. For this purpose I used XML-RSS package from PEAR. Here is snapshot of the code I wrote to process the feed:

  1. <?php
  2. require_once "XML/RSS.php";
  3. //$FeedURL is the URL of the rss feed of an album in picasa
  4. $FeedURL = "";
  5. $rss =& new XML_RSS($FeedURL);
  6. $rss->parse();
  7. $rssArray = $rss->getStructure();
  8. $PicasaDataArray = array();
  9. $InfoArray = array();
  10. for($C=0; $C<count ($rssArray); $C++)
  11. {
  12.    if($rssArray[$C][‘type’] == ‘item’)
  13.    {
  14.       $PicasaDataArray[] = array(
  15.                               ‘title’ => $rssArray[$C][‘title’],
  16.                               ‘image’ => $rssArray[$C][‘enclosures’][0][‘url’],
  17.                               ‘link’ => $rssArray[$C][‘link’],
  18.                               ‘description’ => $rssArray[$C][‘description’],
  19.                               );
  20.    }
  21.    elseif($rssArray[$C][‘type’] == ‘image’)
  22.    {
  23.       $AlbumTitle =  $rssArray[$C][‘title’];
  24.       $AlbumPicture =  $rssArray[$C][‘url’];
  25.       $CreateDate =  $MetaInfo[‘lastbuilddate’];
  26.    }
  27. }
  28. // this $PicasaDataArray contains all the picture related information of an album from picasa web.
  29. ?>

Continue reading ‘Picasa web album slideshow – Development guide’ »