Programmed Under The Influence

Dec 03

“One guy thought he was invisible, the other thought he could fly. Both were wrong. - Steven Seagal”

Replacing Placeholders in PHP

Ran across a neat little function in PHP for replacing multiple placeholder instances within a string.
Here’s an example:

$string = "<strong>##title##</strong><p>##some_text##</p>";
Here’s the PHP:

echo strtr($string,
  array(
    '##title##' => "The Spice...",
    '##some_text##' => "Will flow!!!"
  )
);
Here’s the result:
The Spice…

Will flow!!!

Nov 29

Converting Non-English Characters in PHP

In my previous post, Removing Non-English Characters in PHP, I provided a way to remove non-english characters, but I found another neat trick to convert these characters into a close ASCII equivalent. Here’s the code:

function unaccent($string) {
    if (strpos($string = htmlentities($string, ENT_QUOTES, 'UTF-8'), '&') !== false) {
        $string = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_QUOTES, 'UTF-8');
    }

    return $string;
}
…and here’s the source.

Removing Non-English Characters in PHP

Why would you want to do this, you say?

Well, I found out the other day a payment processor we use (Authorize.net) at the company I work at doesn’t allow for non-english characters and in return, throws a cryptic error.

Here’s the error:
E00003 - Invalid character in the given encoding. Line 15, position 54.

Here’s the trick:
$str = preg_replace('/[^\00-\255]+/u', '', $str);


…and here’s my sources and #2.

Sep 26

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

Sep 03

[video]

Aug 29

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
}

Aug 19

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

Aug 14

Converting ZIP to State Abbr. (using PHP) -

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

Aug 13

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)