String Conversion Functions

I had been doing some nerdy spring-cleaning and found this while digging through the ‘junk’ folder. Maybe useful so I’m posting it here.

// Convert ASCII Text to Binary
function text2bin($string) {
    $string_array = explode("\r\n", chunk_split($string, 1));
    for ($n = 0; $n < count($string_array) - 1; $n++) {
        $newstring .= substr("0000".base_convert(ord($string_array[$n]), 10, 2), -8);
    }
    $newstring = chunk_split($newstring, 8, " ");
    return $newstring;
}

// Convert Binary to ASCII Text
function bin2text($string) {
    $string = str_replace(" ", "", $string);
    $string_array = explode("\r\n", chunk_split($string, 8));
    for ($n = 0; $n < count($string_array) - 1; $n++) {
        $newstring .= chr(base_convert($string_array[$n], 2, 10));
    }
    return $newstring;
}

// Convert ASCII Text to Hexadecimal
function ascii2hex($string) {
    return chunk_split(bin2hex($string), 2, " ");
}	

// Convert Hexadecimal to ASCII Text
function hex2ascii($string) {
    $string = str_replace(" ", "", $string);
    for ($n=0; $n < strlen($string); $n+=2) {
        $newstring .=  pack("C", hexdec(substr($string, $n, 2)));
    }
    return $newstring;
}

// Convery Binary to Hexadecimal
function binary2hex($string) {
    $string = str_replace(" ", "", $string);
    $string_array = explode("\r\n", chunk_split($string, 8));
    for ($n = 0; $n < count($string_array) - 1; $n++) {
        $newstring .= base_convert($string_array[$n], 2, 16);
    }
    $newstring = chunk_split($newstring, 2, " ");
    return $newstring;
}

// Convert Hexadecimal to Binary
function hex2binary($string) {
    $string = str_replace(" ", "", $string);
    $string_array = explode("\r\n", chunk_split($string, 2));
    for ($n = 0; $n < count($string_array) - 1; $n++) {
        $newstring .= substr("0000".base_convert($string_array[$n], 16, 2), -8);
    }
    $newstring = chunk_split($newstring, 8, " ");
    return $newstring;
}

php5 Cookie Class (mmm…. cookies!)

A php5 class for dealing with cookies. Technically it requires php 5.2 because of the added ‘httponly’ option but removing any reference to it will allow it to run under any 5.x build.

Example usage:

require 'cookies.class.php';
$cookie = new cookies('360000'); // Pass expiration value

if ($cookie->set('example', 'example') === TRUE) { // Pass cookie name and value
echo 'Cookie is set!';
 }
echo $cookie->value('example');

Here’s the full code:

<?php

/**
 * ------------------------------------------------------------------------------------------------
 * php class for cookie manipulation.
 *  - Sets, deletes, checkes existance of, and returns values from cookies.
 * ------------------------------------------------------------------------------------------------
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
 * the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program. If
 * not, see <http://www.gnu.org/licenses/lgpl.html>
 * ------------------------------------------------------------------------------------------------
 * @author          Chris Sprague (chris@chaoscontrol.org)
 * @license         LGPL http://www.gnu.org/licenses/lgpl.html
 * @link            http://chaoscontrol.org
 * @version    	    1.0.0
 * @requires        php 5.2.0
 * ------------------------------------------------------------------------------------------------
 */

 class cookies {

    /* Class Variables ------------------------------------------------------------------------- */

    /**
     * Name of the cookie
     * @var $mixed
     */
    public $name;

    /**
     * Class constructor
     *
     * @param int $expires Number of seconds until cookie expires
     * @param mixed $path
     * @param bool $secure
     * @param bool $httponly
     */
    public function __construct($expires, $path = '/', $secure = FALSE, $httponly = FALSE) {
        $this->expiration = $expires;
        $this->path = $path;
        $this->domain = '.' . $_SERVER["SERVER_NAME"];
        $this->secure = $secure;
        $this->httponly = $httponly;
    }

    /**
     * Deletes a cookie
     *
     * @param mixed $name
     * @return bool
     */
    public function delete($name) {
        if (headers_sent() === FALSE) {

           setcookie (
                $name,
                "",
                time() - 3600 * 25,
                $this->path,
                $this->domain,
                $this->secure,
                $this->httponly);

            // Confirm Deletion
            if ($this->check($name) === FALSE) {
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * Creates a cookie
     *
     * @param mixed $name
     * @param mixed $data
     * @return bool
     */
    public function set($name, $data = '') {
        if (headers_sent() === FALSE) {

            setcookie (
                $name,
                serialize($data),
                time() + $this->expiration,
                $this->path,
                $this->domain,
                $this->secure,
                $this->httponly);

            // Set $_COOKIE value for same page load
            $_COOKIE[$name] = serialize($data);

            // Confirm Set
            if ($this->check($name) === TRUE) {
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * Returns the value of a cookie
     *
     * @param mixed $name
     * @return mixed
     */
    public function value($name) {
        if ($this->check($name) === TRUE) {
            return unserialize($_COOKIE[$name]);
        }
        return FALSE;
    }

    /**
     * Check the existance of a cookie
     *
     * @param mixed $name
     * @return bool
     */
    public function check($name) {
        return isset($_COOKIE[$name]);
    }
}

Last.FM Top Albums WP Plugin

I’ve been meaning to package this into a proper WordPress plugin but.. one day. In the meantime, here it is in it’s raw form.

What it does is get your top albums from Last.FM and displays the album art in a pretty table. The XML file gets cached so it wont make an API call to the Last.FM servers on each page load.

It uses simplexml so you’ll need to be running at least php 5.

Dirty Install: Add your username and API key, create a folder in your wordpress plugins directory called CCO-LastFM_Top_Albums and save the below code in index.php of said directory. Call the function in your template.

* I should note that this has been minimally tested.

<?php
/*
Plugin Name: Last.FM Top Albums
Plugin URI: http://www.chaoscontrol.org/wordpress/lastfm-top-albums-wp-plugin
Description: Gets your top played albums (with art) from last.fm
Version: 1.0
Author: Chris Sprague
Author URI: http://www.chaoscontrol.org/about
License: GPL2
*/

/*  Copyright 2011  Chris Sprague  (email : chris@chaoscontrol.org)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
function last_fm_top_albums() {

    // Your Last.FM Username
    $user = '';
    // Last.FM API Key (http://www.last.fm/api/account)
    $api = '';
     // overall | 7day | 3month | 6month | 12month
    $period = "7day";
    // Number of albums to pull
    $limit = '10';
    // Number of rows to display on
    $rows = '2';                               

    $as = 'http://ws.audioscrobbler.com/2.0/';
    $method = '?method=user.gettopalbums';

    $uri = $as;
    $uri .= $method;
    $uri .= '&user=' . $user;
    $uri .= '&period=' . $period;
    $uri .= '&limit=' . $limit;
    $uri .= '&api_key=' . $api;

    $cachedFile = WP_PLUGIN_DIR . '/CCO-LastFM_Top_Albums/' . $user . '.xml';
    $cachedTTL = '300'; // Number of seconds

    if (!file_exists($cachedFile) OR (filemtime($cachedFile) < time() - $cachedTTL)) {
            $xml = file_get_contents($uri);
            $fh = fopen($cachedFile, 'wb+');
            fwrite($fh, $xml);
            fclose($fh);
    }

    $xml = simplexml_load_file($cachedFile);
    $div = $limit / $rows;
    $i = 1;

    echo '<p>';
    foreach ($xml->topalbums->album as $album) {
        echo '
        <a href="' . $album->url . '">
            <img src=' . $album->image . ' />
        </a>';

        if ($i >= $div) {
            echo '</p><p>';
            $i = 1;
        } else {
            $i++;
        }
    }
    echo '</p>';
}