Recent News

Developing web application with PHP-MySql-Apache in Ubuntu Linux

Posted by admin on July 5th, 2008

I have started using Ubuntu 8.04 in few days ago and found it Great. So, now I’ve moved my development environment from windows and working in Ubuntu. Here I am just explaining what steps I had to take for this jump. Also have a listing of some development related softwares/tools which I am using as replacement of windows applications.

Installing Apache, Php5, MySql in Ubuntu:

You can install Apache, Php, Mysql and other applications from Synaptic Package Manager. Go to System > Administration > Synaptic Package Manager and search with your desired application name. When found, double-click on package name. The package will be marked for installation along with it’s dependences. Now click on apply button to install the package. In this post, the red+bold texts are the name of software package which can be installed from Synaptic Package Manager.

To make your system ready for PHP development, you have to install more or less this packages: apache2.2-common, apache2-utils, php5, mysql-server-5.0, mysql-client-5.0, mysql-query-browser etc. You may also require some common php extensions which may not installed automatically with PHP installation. Most of them also will be found in Synaptic Package Manager as php5-gd, php5-curl, php5-mysql, php-pear etc.

Paths of important directories

One of the major differences I find here is the file system. All the directory paths I’ve been using in windows are changed here. I m listing here some PHP-MySql related paths here. But they may differ on your installation.

  • Apache configation files: /etc/apache2/
  • localhost root directory: /var/www/
  • PHP ini file: /etc/php5/apache2/
  • PHP extensions configuration files : /etc/php5/conf.d
  • MySql Data files: /var/lib/mysql/mysql
  • MySql Configuration files: /etc/mysql/

PHP Editors for Ubuntu

Gedit is the default text editor of Ubuntu and it support syntax coloring for many languages including PHP. But If you want an advanced editor for programming, you can try Geany or Screem. But, I am sure, who’ve been using advanced IDEs like PHPEd or PHPDesigner in windows, none of this can satisfy him. Don’t worry, the great open source IDE eclips has PHP-Development-Tool. It’s surely one of the best PHP IDE.

Subversion in Ubuntu

Subversion maintains current and historical versions of source code and documentation. It’s very important for distributed application development. RapidSVN is a graphical client for the subversion revision control system (svn) for linux. If you want to use svn from command line, install subversion.

File Difference and Merging Tools for Ubuntu

I have been using WinMerge in windows as file comparison and merging tool along with TortoiseSVN. Now using TkDiff as it’s alternative in linux. TkDiff has advanced functionalities and graphical interface. It provides file-merge and change-summary facilities, line number toggling (for easier cut & paste) and support for Subversion, RCS, CVS and SCCS. To use from command line, diff is may be the simplest file comparison tool.

Ftp and SSH

Ubuntu installs its default programs for FTP, SSH and many other internet applications. But, I’ve liked gFTP as FTP application because of it’s interface is similar to SmartFTP. And for working with SSH, required nothing. Just open the terminal and use ssh command. Write something like ssh username@example.com and press ENTER.

Testing in IE

One of the important (and painful to me) issue of web development is testing the output in IE. Though IE has no version for Linux, you can install it through wine. Wine is a application that crates a virtual environment for installing windows applications in Linux. After installing wine, you can install any available version of IE from http://www.tatanka.com.br/ies4linux/page/Installation:Ubuntu.

When witting this post, my aim was to help a developer who is thinking to switch to Ubuntu Linux or a newcomer here. You are welcome to add your valuable comment/suggestion for the same purpose.

PHP Universal Feed Parser - lightweight PHP class for parsing RSS and ATOM feeds.

Posted by admin on May 2nd, 2008

After the PHP Universal Feed Generator, I’ve written the PHP Universal Feed Parser for Orchid Framework. It’s a RSS and ATOM parser written in PHP5. Though there are many feed parsers over Internet, none of those was serving the basic focuses of Orchid: pure object orientation, being lightweight etc. So, I had to write a new one.

UPDATE(15th May, 2008) : cURL support added. Where url fopen() is disabled, the class will use cURL to load the RSS/ATOM content.

Features:

  • Parses all channels and feed item tags and sub tags.
  • Serve the parsed data as associative array.
  • Enough documented and easy to understand code.
  • Many ways to get parsed information.
  • Parsing includes attributes too.
  • No regular expression used.
  • Parsed by XML Parser extension of PHP.
  • Pure PHP5 objected oriented.
  • Enable to parse all commonly used feed versions.

Supported versions: I tried to include all stable and commonly used feed versions. Currently it’s being used to parse the following versions:

  • RSS 1.0
  • RSS 2.0
  • ATOM 1.0

Download:

  • Click Here to get the class file with example. (downloaded 481 times)
  • Download from phpclasses.org.

How to use:

It’s dead simple to use this class. Just follow this 3 steps:

1. Include the file

include(’FeedParser.php’);

2. Create an object of FeedParser class

$Parser = new FeedParser();

3. Parse the URL you want to featch

$Parser->parse(’http://www.sitepoint.com/rss.php’);

Done.

Now you can use this functions to get various information of parsed feed:

  • $Parser->getChannels() - To get all channel elements as array
  • $Parser->getItems() - To get all feed elements as array
  • $Parser->getChannel($name) - To get a channel element by name
  • $Parser->getItem($index) - To get a feed element as array by it’s index
  • $Parser->getTotalItems() - To get the number of total feed elements
  • $Parser->getFeedVersion() - To get the detected version of parsed feed
  • $Parser->getParsedUrl() - To get the parsed feed URL

A simple example:

Here is a simple example of using this Feed Parser class. Click here to see is the output of this example.

<?php 
include(‘FeedParser.php’); 
$Parser     = new FeedParser();
$Parser->parse(’http://www.sitepoint.com/rss.php’);
 
$channels   = $Parser->getChannels();     
$items      = $Parser->getItems();        
?>
<h1 id=”title”><a href=”<?php echo $channels[‘LINK’]; ?>><?php echo $channels[‘TITLE’]; ?></a></h1>
<p id=”description”><?php echo $channels[‘DESCRIPTION’]; ?> </p>
 
<?php foreach($items as $item): ?>
    <a class=”feed-title” href=”<?php echo $item[‘LINK’]; ?>><?php echo $item[‘TITLE’]; ?></a>
    <p class=”feed-description”><?php echo $item[‘DESCRIPTION’]; ?></p>
<?php endforeach;?>

I hope, this class is so easy that, anyone who have general knowledge about PHP5 can use it. Whatever it is, Feel free to ask me anything, anytime.

PHP Universal Feed Generator (supports RSS 1.0, RSS 2.0 and ATOM)

Posted by admin on March 8th, 2008

It’s been a while since I’ve planned on developing a RSS writer that fulfills most my needs by supporting the various feed formats. Although the necessity was the prime force behind it, a discussion with Hasin and Emran has put the actual fire in. We were discussing about what can be added next in the Orchid - “PHP framework for the rest of us” and suddenly it hit me. At last, it’s finally complete and I’ve named it "PHP Universal Feed Generator", as it generates both ATOM and RSS feeds.

Supported versions:

  • RSS 1.0 (which officially obsoleted RSS 0.90)
  • RSS 2.0 (which officially obsoleted RSS 0.91, 0.92, 0.93 and 0.94)
  • ATOM 1.0

Download: 

Features:

  • Generates RSS 1.0, RSS 2.0 and ATOM 1.0 feeds
  • All feeds are are validated by feed validator.
  • Supports all possible feed elements.
  • Simple and easy to define channel and feed items
  • Implements appropriate namespaces for different versions.
  • Automatically converts date formats.
  • Generates UUID for ATOM feeds.
  • Enables usage of subtags and attributes. (example: image and encloser tags)
  • Completely Object oriented in PHP5 class structure.
  • Handles CDATA encoding for required tags.
  • Nearly same code for generating all kinds of feed

A minimum example

It’s a minimum example of using this class. I am generating a RSS 2.0 feed from retrieved data from a MySQL database. There are more examples in the download package for different versions.

<?php
  // This is a minimum example of using the Universal Feed Generator Class
  include("FeedWriter.php");
  
  //Creating an instance of FeedWriter class. 
  $TestFeed = new FeedWriter(RSS2);
  
  //Setting the channel elements
  //Use wrapper functions for common channel elements
  $TestFeed->setTitle(‘Testing & Checking the RSS writer class’);
  $TestFeed->setLink(‘http://www.ajaxray.com/projects/rss’);
  $TestFeed->setDescription(‘This is test of creating a RSS 2.0 feed Universal Feed Writer’);
  
  //Image title and link must match with the ‘title’ and ‘link’ channel elements for valid RSS 2.0
  $TestFeed->setImage(‘Testing the RSS writer class’,‘http://www.ajaxray.com/projects/rss’,‘http://www.rightbrainsolution.com/images/logo.gif’);
  
    //Retriving informations from database
    mysql_connect("server", "mysql_user", "mysql_password");
    mysql_select_db("my_database");

    $result = mysql_query("Your query here");

 
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        //Create an empty FeedItem
        $newItem = $TestFeed->createNewItem();
        
        //Add elements to the feed item    
        $newItem->setTitle($row[‘title’]);
        $newItem->setLink($row[‘link’]);
        $newItem->setDate($row[‘create_date’]);
        $newItem->setDescription($row[‘description’]);
        
        //Now add the feed item
        $TestFeed->addItem($newItem);
    }
  
  //OK. Everything is done. Now genarate the feed.
  $TestFeed->genarateFeed();
?>

Shhhh….a universal feed reader is on the way ;)

PHP UUID generator function

Posted by admin on February 6th, 2008

Universally Unique Identifier is an identifier standard which is used in a varieties of software construction. When I was writing the RSS Writer class for Orchid, I needed to generate UUID to implement with ATOM id. I searched the web for a simple solution, but didn’t find any that suffices my need. Then I wrote the following function to generate it. I’ve use the standard of canonical format here.

Let’s take a look what Wikipedia has to say about the format of UUID :

A UUID is a 16-byte (128-bit) number. The number of theoretically possible UUIDs is therefore 216*8 = 2128 = 25616 or about 3.4 × 1038. This means that 1 trillion UUIDs would have to be created every nanosecond for 10 billion years to exhaust the number of UUIDs.

In its canonical form, a UUID consists of 32 hexadecimal digits, displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters.

Enough said. Here is the function.

/**
  * Generates an UUID
  * 
  * @author     Anis uddin Ahmad <admin@ajaxray.com>
  * @param      string  an optional prefix
  * @return     string  the formatted uuid
  */
  function uuid($prefix = ) 
  {
    $chars = md5(uniqid(rand()));
    $uuid  = substr($chars,0,8) . ‘-’;
    $uuid .= substr($chars,8,4) . ‘-’;
    $uuid .= substr($chars,12,4) . ‘-’;
    $uuid .= substr($chars,16,4) . ‘-’;
    $uuid .= substr($chars,20,12);
    
    return $prefix . $uuid;
  }

Example of using the function -

//Using without prefix.
echo uuid(); //Returns like ‘1225c695-cfb8-4ebb-aaaa-80da344e8352′ 
 
//Using with prefix
echo uuid(‘urn:uuid:’);//Returns like ‘urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344e8352′
 

See you.

UPDATE : The PHP Universal Feed Generator class, for which I wrote this function is released.

How to avoid POSTDATA resend warning

Posted by admin on January 12th, 2008

"POSTDATA resend" warning is a common problem when developing web applications. Before discussing about the solution, let’s know what is the problem actually and when it arises.

About the problem :

We see this warning when we try to revisit a page that has accepted POSTDATA using browser’s history mechanism. Usually we do it by browser’s BACK button or refreshing a page. When a page in browser history requested with POST method, the browser thinks this POSTDATA is important to process this page. So, it asks the user if he wants to send the POSTDATA again or not. Different browsers show this warning differently. For example, the images below shows how Firefox and Internet Explorer show this warning.

POSTDATA_resend_mozilla

POSTDATA resend warning in Mozilla Firefox

POSTDATA_resend_ie

POSTDATA resend warning in Internet Explorer

 

Now, If the user accepts the confirmation, the page is reloaded with previously sent data using POST method; otherwise some browsers don’t take any action and some shows a "Webpage has expired" message. In some situations, this re-submitting is useful, but most of the times it’s not expected. It’s more harmful when user accepts it without understanding and causes multiple entries of previously entered data in database.

The easy solution :

The easy solution is simply redirecting. When we redirect a page, the target page is loaded without any POST data that comes with request.

Let’s solve this problem by hand. Say we have 2 pages - A and B. A has a feedback form which submits data by POST request method to B. B inserts the information into database and shows a success message.

Now, if the user try to reload the page by refresh, back button or any other way, browser will show the confirmation message. If user accepts this, the message will inserted again. But after inserting to database, If we redirect to another page C and C shows the success message, the problem will not occur. Because, in the final output to the browser will come from C which didn’t use any POST request data. The code should be something like this:

<?php
if($_POST)
{
  /* Form validation, Inserting to database or anything you want goes here */
  
  /* Now redirect to another page */
  header(‘Location: http://yoursite.com/success.php’);
}
?>

 

Extending the solution :

The solution I explained above can show just an static message like "Thanks for your feedback" or "Registration completed successfully" etc. But usually we like to include some information about sender or submitted information in the success of failure message. For example:

Hi Andrew, your registration is successfully completed. An email is sent to you at andy001@yahoo.com with more information.

In the above message, the purple colored information has to be taken from POST data. But the POST data will be lost when redirecting. So, it’s not possible by the above solution.

What we can do to solve this is that we can use SESSION to store those data which we want to display with message in redirected page. Just like this:

<?php
session_start();
 
if($_POST)
{
  /* Form validatio, Inserting to database or anything you want goes here */
  
  //Store data to session
  $_SESSION[‘name’]   = $_POST[‘name’];
  $_SESSION[‘email’]  = $_POST[‘email’];
  
  //Now redirect to another page 
  header(‘Location: http://yoursite.com/success.php’);
}
?>

 
In the target page, when showing the success message, we can get the information from SESSION easily.
 
Hope this will solve your problem. Please tell me if any confusion or question with this article.  See you again.

“How to add archive functionality to your PHP app”

Posted by admin on September 26th, 2007

“An archive refers to a collection of records, and also refers to the location in which these records are kept. Archives are made up of records which have been created during the course of an individual or organization’s life.” - Wikipedia.

Archive is an essential feature of a well defined blog system. If you have a blog in blogger or wordpress, you’ll get built-in archive feature there. But if you are making a blog yourself or any similar application, you might need to add this function yourself. These are some ideal example of archives:

Omar Al Zabir www.phpfour.com somewherein bangla blog

I’ve done it for one of my app and here I am telling you the time saving tip: creating an archive function in 3 easy steps.

1. Generate organized archive data: Generally, archives are created on create date of contents. Let’s say, your blogs table has a field named create_date which holds the timestamp of the post. Now, you can get your archive data in very organized format with this simple yet powerful query (it’s in MySQL):

SELECT COUNT(id) total, MONTHNAME(create_date) month, YEAR(create_date) year

FROM blogs

GROUP BY MONTH(create_date), YEAR(create_date)

ORDER BY create_date

Note that you’ll need to use where clauses if there are any condition. The output of your query should look like this:

Query to retrieve archive data The result
image image

 

2. Use the archive data: After you have retrieved the archive data, you can display them in any sidebar of your application. A sample code can be as follows:

 

 1: <h4>Older Entries</h4>
 2: <ul>
 3: <?php foreach ($archive as $month): ?>
 4: <li>
 5: <a href="<?php echo $month[’year’] . "/" . $month[‘month’] ?>">
 6: <?php echo $month[‘month’] . " " . $month[‘ year’] ."(" . $month[‘total’] .")" ?>
 7: </a>
 8: </li>
 9: <?php endforeach; ?>
 10: </ul>

So, what’s done here? Well, it displays the archive sets with an appropriate link. Note that the link are created in “clean URL” style, i.e. yourdomain.com/2007/july – if you are using an MVC framework like CodeIgniter or CakePHP, you may find it easy to integrate. You can of course create it in the old style, by changing the above code in this way:

 1: <li>
 2: <a href="blog.php?year=<?php echo $month[‘year’] ?>&month=<?php echo $month[‘month’] ?>>
 3: <?php echo $month[month‘] . " " . $month[’ year ‘] ."(" . $month[’total‘] .")" ?>
 4: </a>
 5: </li>

3. Display related posts: And now you’ll need to handle the fetching of appropriate posts based on the passed archive information (year and month), but that’s something that only you can figure out, as I don’t know what you have in there.

Happy Blogging…Happy Archiving :)

Ajax-like Unobtrusive File Upload

Posted by admin on July 28th, 2007

We use AJAX whenever we need to communicate with the server, without reloading the page. But this doesn’t function in the case of File Upload. In usual view, uploading files with AJAX is impossible! (FireFox/Mozilla can do this after change a setting in “about:config” – which we cannot guarantee for a lot of users).

When I was searching for any technique to upload file without reloading page, I found a script in www.webtoolkit.info . But it seemed very complex to me. Then I try to simplify their technique and its working great. So I thought why not share the technique with everybody?

First, look at the demo here to see how it works.

OK. Let’s get into the deep. What happens when we submit a form? The form is submitted to the action page and that page loaded in current frame of window. If the “target” attribute of form indicate “_blank” or any frame name of the window, the page loads in a blank window or in the named frame or inner frame. Here we’ll be using the second method.

First, take an inner frame in anywhere of the page. And set the display property of this frame as “none”:

    <iframe name="hiddenFrame" id="hiddenFrame" 
    src="about:blank" style="display:none" >
    </iframe> 

Now, just set this frame as the target of your uploading form.

<form name="testForm" id="testForm" enctype="multipart/form-data" 
    action="upload.php" method="post" target="hiddenFrame">
        <input type="file" name="name" /> 
        <input type="submit" value="Upload!" />
    </form>

If we submit this form now, it will submit the file to the target script on the server (can be in php, asp etc.). The script will upload the file and will load the response in the frame “hiddenFrame”. As the frame is not visible, nothing about this loading will be seen by the visitors. Now, as the uploading page displays nothing after uploading your file, the response can be immediate. Although it’s not AJAX, this technique will upload your file without (visually) reloading page.

What more?

For many purpose, we might need a callback function when using AJAX. For this file uploading technique also, we will try to create something like that. First, we’ll write the callback function as a simple JavaScript function in the header of the uploading page:

<script language="javascript">
function trackThis()
{
var resultDiv = 
    window.frames.hiddenFrame.document.getElementById(‘result’);
var uploadedImage = document.getElementById(‘UploadedImage’);

uploadedImage.src = resultDiv.innerHTML; 
uploadedImage.style.display="block";

alert("File Uploaded :" + resultDiv.innerHTML);
}
</script>

When the uploading of the server page is complete, it should print the JavaScript code in the hidden iframe, to call the callback function with the reference “window.top”. Any other required information also can be printed in specific DIVs. It will enable us to retrieve any response information using the innerHTML of any specific DIV (as shown in example callback function).

Example:

<?php
print_r($_FILES["name"]);
if(move_uploaded_file($_FILES["name"]["tmp_name"], 
            dirname(__FILE__)."/".$_FILES[‘name’][‘name’]))
{
echo "Your uploaded file is: <div id=’result’>".$_FILES[‘name’][‘name’]." </div>";
}           
else
{
    echo "<div id=’result’>Sorry! Error occured!</div>";  
}
echo <<<test
<script type="text/javascript">
window.top.trackThis()
</script>
test;
?>

Well, that’s it. This technique has already saved my ass once, see if it can save yours also when you need.

Recent Comments | Recent Posts


designed by: Website Builder | Coded by: Blog Directory | Provided by: Wedding photojournalism chicago
bottom