Programmed Under The Influence
Creating a forum/chat room hybrid system

I’ve been asked a few times so far to create a chat room for one of my sites. Now even though I think this is an interesting request, I find that chat rooms have become a thing of the past, which have been taken up by the older Internet crowd and (sadly) cyber-predators (no, not like the one Schwarzenegger fought).

I did some thinking and a friend of mine helped me come up with an idea to create a forum/chat room hybrid. It would have the visual & functional qualities of a forum, but would be updated dynamically using sort of what you now find on Twitter’s real-time search results where you are notified of new posts on a timely basis. I’m not going to go into very much detail cause I had to make it work for my site specifically, but I’ll give you an idea on how it works so you can take it in any direction you want to.

What you’ll need… HTML, PHP, jQuery, and a MySQL database

First thing first, let’s see a quick look at what the HTML code will look like (again, this is really basic). *Note: we are setting a session to keep track of when the user first got to the page so we aren’t loading posts that aren’t “new”:

<?php $_SESSION['last_refresh'] = date('Y-m-d H:i:s'); ?>

<div id="new_posts_msg" style="display: none;"> </div>
<div id="forum_posts">
    <div class="forum_post">First!</div>
    <div class="forum_post">Second post!</div>
    <div class="forum_post">Third!</div>
</div>

Next, we need to set up a timer that will kick off the update function (which fires when the document is ready) and have it run every so often (mine fires every 20 seconds):

$(document).ready(function() {
    setTimeout('checkForNewPosts()', 20000);
}

Now let’s take a look at the function that will call a background script to check for new posts and display a button telling the user that there are new posts:

function checkForNewPosts() {
    $.post('checkForNewPosts.php',
        function(data) {
            if (data > 0) {
	        $('#new_posts_msg')
                .html('<button type="button" onclick="loadNewPosts()">
                  New posts! Click to load them.</button>')
                .fadeIn('slow');
	    }
        });
    
    // Check again in 20 seconds
    setTimeout('checkForNewPosts()', 20000);
}

Let’s take a look at what’s happening on the “back-end” (or the checkForNewPosts.php file). Using the session we set from last time, we will select any “new” posts that weren’t loaded when the page was first loaded. The result is then sent back to the javascript function to display the “new post” notification button if any new posts have been added:

<?php // check for new posts in our `forum_posts` table
    $query = "SELECT COUNT(*) AS new_post_count
        FROM forum_posts
        WHERE forum_posts.added
          BETWEEN '" . $_SESSION['last_refresh'] . "' AND NOW()";
    $result = $this->query($query);
    
    // Return to display notification
    echo $result[0]['alias']['new_post_count'];
?>

If you noticed before, the “new post” notification button had an onclick function called loadNewPosts(). This is shown below and is used to load all the new posts that were found:

function loadNewPosts() {
    $.post('loadNewPosts.php',
        function(data) {
            $('#new_posts_msg').html('').hide(); // Hide the button
            
            // Display new posts
            $('#forum_posts').find('.forum_post:last').after(data);
        });
}

Finally, the loadNewPosts.php file is responsible for retrieving all the new posts and adding them after the latest post already loaded:

<?php
    $query = "SELECT *
        FROM forum_posts
        WHERE forum_posts.added
          BETWEEN '" . $_SESSION['last_refresh'] . "' AND NOW()";
    $result = $this->query($query);
    
    $new_posts = "";
    foreach ($result as $row) {
        $new_posts .= "<div class="forum_post">" .
            $row['forum_posts']['post'] .
            </div>";
    }
    
    // Return to display new posts on web page
    echo $new_posts;
?>

I hope that all made sense and helps you in your endeavors to make a dynamically-tubular website. For a working demo, please check out an active thread at: One Line Rhyme :: Forums

imagecopyresized - grainy, but quick

imagecopyresized - grainy, but quick

imagecopyresampled - smooth, but slow

imagecopyresampled - smooth, but slow

I was working on the Account Settings page for one of my personal sites today and I noticed that the resized images I was uploading for test purposes were very pixelated. Then I noticed that my image resizing class was using imagecopyresized to resize the images. I decided to do some research and found that imagecopyresized is quick and dirty, while imagecopyresampled is more CPU intensive, but keeps some of quality making the image smoother and clearer in the end. Luckily for me I don’t allow larger than 50K uploads on my site so I’m now using imagecopyresampled.

Parsing RSS feeds using SimpleXML

I’m was working with Last.fm’s API service to post user’s recent tracks on one of my sites. I wanted a lighter solution to using their REST Request method so I opted to use their RSS feeds instead. In the past I used either Magpie or SimplePie to parse the RSS for easy access, but I didn’t want the overhead of both these services so I did some research and found something of use courtesy of Stuart Herbert’s article, “Using SimpleXML To Parse RSS Feeds.”

I’ll give a brief tutorial on how I used Stuart’s tutorial to display my 10 most recent tracks from Last.fm:


// Get the RSS URL and plug in your ~username~
$lastfm_feed = "http://ws.audioscrobbler.com/1.0/user/~username~/recenttracks.rss";

// Turn the feed into a string and load it using PHP's simpleXML function
$raw_feed = file_get_contents($lastfm_feed);
$xml = simplexml_load_string($raw_feed);

// Next throw the results into a foreach loop to display the results
// I'll just display all the values you can print out
foreach ($xml->channel->item as $item) {
    echo $item->title; // Track title
    echo $item->link; // Link back to the track on Last.fm
    echo $item->pubDate; // Date the track was played
    echo $item->guid; // Unique identifier
    echo $item->description; // Links back to the artist's page
}
Pollacio.us is here!!

My newest edition has arrived….

Pollacio.us Logo

Pollacio.us is a website with a simple concept. You create a survey, invite your friends to vote, and watch as the results come in. Democracy at it’s best, yea yea!!

Have you ever had to make plans with a group of friends and never know what to do? Pollacio.us has the tools to help you and your friends decide on what to do as a group.

The site has a comfortable feel (logo courtesy of sxtxixtxcxh), it’s easy to use (I hope), and most importantly is free to join! So please register and start creating surveys :D

Cool “little” script for converting a 5 digit ZIP code to a 2 letter state abbreviation.

Dawn of the Surprise Squirrel!!
(Photo from the movie: Dawn of the Dead - 2004)

Dawn of the Surprise Squirrel!!

(Photo from the movie: Dawn of the Dead - 2004)
Bike Crash (Surprise) Squirrel!!
(Original image from: http://www.rofl.name/)

Bike Crash (Surprise) Squirrel!!

(Original image from: http://www.rofl.name/)
Nuclear (Surprise) Squirrel!!
(Original image from: http://science.howstuffworks.com/)

Nuclear (Surprise) Squirrel!!

(Original image from: http://science.howstuffworks.com/)
Surprise Squirrel!! (at least that&#8217;s what I call him)
(Source: http://www.telegraph.co.uk/news/newstopics/howaboutthat/6018173/Squirrel-is-surprise-star-of-holiday-photo.html)

Simple - choose one

Simple - choose one

Ranked - order options from good to bad

Ranked - order options from good to bad

Range - score each option from 0 to 5

Range - score each option from 0 to 5

Approval - choose all options you like

Approval - choose all options you like

Weighted - divvy up 5 pts to all options

Weighted - divvy up 5 pts to all options

5 flavors of voting. Choose which one best suits your survey.