Posterous theme by Cory Watilo

PHP Gallery With Pagination Goodness Within Five Minutes

Familiarity: HTML/XHTML/HTML5 + CSS + PHP

Time Required: 5 Minutes or less

 

You can do really neat things with the raw power of Arrays. I showed you an example of parsing Multidimensional arrays in PHP in my previous post. In this post, I'm going to show you how to create a PHP gallery within 5 minutes. The basic assumption is that the reader is familiar with XHTML/CSS and general programming buzz words (e.g. variables, functions, strings, arrays, etc.)

Here's what we'll be creating at the end of this post:

Simple-php-gallery-snapshot
Simple-php-gallery-snapshot2
There, a pretty simple gallery that has been sexified (if that is even a term) using Lightbox 2 and has raw pagination powers, thanks to the array_chunk() PHP function. Okay, before you get totally impatient to see how does this work, I should better start showing you "how":

First, let's create a basic markup structure:

Save the file as "index.php" in your root project directory, i.e., Gallery. Notice that I've downloaded Lightbox 2, extracted it to the project directory (Gallery, in this case) and linked the downloaded files from our main index.php file.

Now the CSS part (css/gallery.css)

Now is the time to get PHP back! Create a new file named "gallery.php" in the project root directory and type this code:

As you can see, I've wrapped the code inside a function for portability. The function takes one argument -- $path. Save the script and return back to "index.php". In this file, you need to do only two things to get the Gallery running:-

  • Include the PHP code file, gallery.php, using include()
  • Call the function -- genGallery(), supplying the required parameter.

 

That's it! Demo

Note that there are lots of things that can be improved even in this tiny little script. And there are way too many nice little things that could make this gallery a rockstar! But, I only had 10-15 minutes to create this script and write this post so.. 

If I were to spend an hour on this script, it'd had all these things:

  • Check proper file extensions (pretty easy to implement)
  • Fetch EXIF data and display it nicely using the powerful of JavaScript or your favorite JS Library.
  • Add "star rating" feature so people could give your image FIVE STARS! 
  • Add tagging support
  • Add commenting
  • Pretty URLs
  • CRUD, preferably using SQLite
  • Authentication, using SQLite

Might sound like a lot but all the things listed above are pretty easy to implement in PHP. Ah, and suppose if Object Orientation was used at that! If you like this post, go ahead and create your versions (including added functionalities/improvements).

Imagine, Learn and Create.

Solving "Write Failed: Broken Pipe" Error

Problem: Write Failed: Broken Pipe

Solution: If you ever face SSH Timeout errors while connecting to your server via SSH, here is what to do:

If you're using Putty, go to Change Settings > Connections and in the "Seconds between keepalives" box, enter 10. If you're using Linux as the client OS, open the /etc/ssh/ssh_config file and add ServerAliveInterval 10 at the end of the file. Save the file.

Now your connection should work properly. Try setting the value a bit higher and see if the error isn't being regenerated. Try experimenting with the value and see how far you can go. For example, if things are working fine at "10" then try setting "20" or "30" or even higher and see if there is any problem.

Fun With Python - Develop a Simple Console Game

Since I started teaching Computer Programming, I've been trying to come up with very simple, fun concepts to help students understand programming languages as easily as possible. One of such concepts is to develop simple games. Here is an example of a pretty simple console game, written in my favorite programming language -- Python.

I'll probably write another fun Python script, this time for Google App Engine (Python) so that you can play with it online.

Understanding Multidimensional Arrays in PHP

Often I get contacted by people regarding their frustration in understanding how Multidimensional Arrays work. This leaves me wondering why is it that difficult to understand Multidimensional Arrays? Maybe the reason that people have a hard time understanding the whole Multidimensional Array concept is because book authors don't take the time to explain Arrays in easy-to-grasp manner.

In PHP, a Multidimensional Array looks like this:

There, a very basic example of a multidimensional array in PHP. And here's how you output the values stored in the "Blog" array:-

Just try viewing the code in your browser and it looks something like this:

Multidarray_output
Look closely and you'll find the last pair of "Property => Value" doesn't show what one might expect it to show. The reason is pretty simple. The "Pages" key of our "Blog" array is not a normal key. It's an array inside an array. If you do a simple "View Source" exercise, you'll get something like this:

Multidarray_output_vs

This is where people tend to get confused. If you follow my advice, there is nothing to worry about. Since we already know that the key "Pages" is an array, this is how we output values stored in the "Pages" property:

The output looks like this:

Multidarray_output_2

Here is a practical PHP example using an EXIF function to output META information stored in image headers:

The output:

Exif-array-output

Now suppose if we only needed to capture the following information from this whole information tree:

 

  • Name : 
  • Make :
  • Model : 
  • Software : 
  • Capture Time :
  • Exposure Time
  • ISO Speed :
  • Image Height :
  • Image Width :
  • CCD :

If you pay attention, capturing all the above information is a pretty simple process:

The output:

Image-meta-output

As you can see, outputting information from a nested array is just a matter of following this simple pattern:

$array['nested-array']['nested-property']

Now, at this stage, some of you might be wondering how can one print out all the "property" => "value" pairs stored in a multidimensional array! Here is how you can achieve this using the built-in is_array() function:

The output:

Selection_009
Now try doing "View Source" and you'll see nicely-tabbed HTML source code. Whenever I'm writing code that sends output to the browser, I try to make sure it looks good even under the hood:

Selection_010

P.S. Editing posts with the Posterous Rich-Text Editor is such a nightmare that it took me over 60 minutes to make this post look good. What a shame there isn't a single option to disable the rich-text editor!

Blog Moved To Posterous

I've moved this blog from WordPress to Posterous. I had four-five options when I decided to make the switch:-

  1. Google App Engine
  2. Blogger
  3. Posterous
  4. Tumblr
  5. GitHub

All of the above services allow you to host your blog/website for free, using your own custom domain. I use Google App Engine for development purposes. It's a great platform, enabling you to host your Python, Java or PHP (almost)-powered websites.

I occasionally use Blogger where I run my very personal blog. But, whenever I decided to move *this* blog to Blogger, I started getting nightmares as soon as I tried to post any source code.

GitHub is a place where you can only host your static websites. Tumblr is a pretty cool micro-blogging platform but it lacks many features of Posterous so from now on, this blog will be using Google App Engine for its dynamic aspect (code demos, etc.) and Posterous as the blogging platform.

I'll still be using WordPress for any serious projects.

Linux Like Window Focus on Mouseover (Win XP)

Just a little tip that I think some of you'll find helpful. As many of you may already be aware, I make extensive use of Open Source tools. For years, I've used Linux/BSD on my home workstations and quite a few times have gained success in convincing my bosses to make the switch but you know, that's not always the case. No matter how you want to avoid Windows, you'll often times come across situations that force you to use Windows, even for a day. One of the things that I hate about Windows is that even though it is a pretty capable operating system, it hides many such capabilities that power users are going to like. One of such capabilities is Change Focus on Mouseover. Normally, you aren't going to find any visible option to enable this feature. In Windows, the default configurations force you to click on the title bar of another window in order to bring it into focus. This is not the case with Linux. Just bring your mouse pointer to a different application window and it becomes focused! I can't explain how much I've missed this feature before I came to realize that this kind of stuff is possible even in Windows operating systems using the RegEdit (Registry Editor) utility. Since editing registry is something that you shouldn't do unless you really know your stuff, I've found a tiny utility that allows you to do the same using point & click method. Go to Microsoft PowerToys and download the TweakUI utility. Here is the direct link. Here is what TweakUI does:
TweakUI gives you access to system settings that are not exposed in the Windows XP default user interface, including mouse settings, Explorer settings, taskbar settings, and more.
After installing it on your system, launch TweakUI from START >> Program Files >> Powertoys for WindowsXP >> Tweak UI. Under Mouse >> X-Mouse, select Activation follows X-Mouse checkbox and click OK.
Media_httpwwwavinashw_enjel
You're done! Try opening a few applications and hovering your mouse over them. Check if windows change focus or not. If you want to see what changed after following the previous procedure, here is a quick screencast: [swf]http://media.avinash.ws/change-window-focus-on-mouseover-windowsxp.swf,930,588[/swf]

Code Faster Using Zen Coding [video]

A short screencast on how to code faster using the Eclipse IDE and Zen Coding. This is my first try at creating screencasts so in case you notice something that needs to be improved (and I'm sure there are many things that can be improved), please do inform me. If you're on a slow connection, the video will take time to load so in that case, download the screencast. P. S. What I realized while creating this screencast is that talking to a person is way easier than recording a screencast. I hope I'll learn how to do it properly.

Syntax Highlighting in Microsoft Word

If you've ever tried copy-pasting source codes into a Word document, you know what a nightmare it is to apply syntax highlighting. Most probably, you have to manually apply colors on sections of source code. While searching for a solution, I came to know about a Notepad++ plugin NppExport that'll help you copy code from Notepad++ and paste it in Microsoft Word with syntax-coloring attached. If you haven't got a copy of Notepad++, download it from their download page. After installing it on your machine, launch Notepad++ and copy-paste this Python source code into a new file:
# This code snippet is a part of the Planet Planet feed aggregator

if feed_timeout:
        try:
            feed_timeout = float(feed_timeout)
        except:
            log.warning("Feed timeout set to invalid value '%s', skipping", feed_timeout)
            feed_timeout = None

    if feed_timeout and not offline:
        try:
            from planet import timeoutsocket
            timeoutsocket.setDefaultSocketTimeout(feed_timeout)
            log.debug("Socket timeout set to %d seconds", feed_timeout)
        except ImportError:
            import socket
            if hasattr(socket, 'setdefaulttimeout'):
                log.debug("timeoutsocket not found, using python function")
                socket.setdefaulttimeout(feed_timeout)
                log.debug("Socket timeout set to %d seconds", feed_timeout)
            else:
                log.error("Unable to set timeout to %d seconds", feed_timeout)
Now go to Language > P > Python to apply syntax highlighting for Python code. You can select other languages depending on your requirements. You'll notice that the source code is now colorful. Now go to Plugins > NPPExport > Copy all formats to clipboard. Selecting this option saves a copy of the selected source code in the clipboard. Launch Microsoft Word and press Ctrl + V to paste the copied source code. Here is how it looks like in Microsoft Word:
Media_httpwwwavinashw_rnfoc
If you're aware of any other method, do let me know in your comments.