PHP

Generating a Dynamic XML or Text Playlist using PHP

Posted in Flash, PHP, Web Development on June 5th, 2011 by Steve Marks – Be the first to comment

If you’ve ever tried to incorporate some kind of Flash music player into your website, you’ll probably notice that it will more than likely contain an option to use a playlist to play multiple songs in sequence. This can work really well if you’ve got a set number of songs that you want to play, not so great however if the songs are constantly changing, coming from a database or are user-contributed.

If this is the case then a standard XML or text file won’t do. Instead I show you below how to use PHP to generate this playlist on-the-fly.

The Solution

For the example below I’ll presume that the playlist is in XML format. Let’s look at the part where we embed the flash player and reference the playlist:

<param name="FlashVars" value="...&playlist=http://www.mydomain.com/playlist.php&..." />

Notice how we reference a PHP file? Let’s take a look at what this playlist.php file might look like. Depending on what you are trying to achieve this will no doubt change. In the example below I’m going to get the latest 5 songs from a MySQL table:

// specify that the output will be xml
header("Content-Type: text/xml");

// establish a connection to the MySQL database
$conn = mysql_connect("localhost", "user", "pass");
$db = mysql_select_db("song_database");

echo '<?xml version="1.0" encoding="UTF-8" ?>
<songs>';

// get 5 latest songs
$query = "SELECT `filename` FROM `songs` ORDER BY `dateAdded` DESC LIMIT 5";
$result = mysql_query($query);
while ($row=mysql_fetch_assoc($result)) {
    echo '<song>'.$row['filename'].'</song>';
}

echo '</songs>';

So there we have it. If a song was to get added, the playlist would update automatically without having to manually change the static playlist file.

Some Considerations

Caching

Flash has a tendancy to cache files that it uses which, as a result means the dynamic playlist being included might not update automatically. If this is a problem for you, one way to get around this would be to add a changing parameter to the end of the filename like so:

<param name="FlashVars" value="playlist=http://www.mydomain.com/playlist.php%3F<?php echo time(); ?>" />

PHP files not accepted as playlist FlashVar

Some music players specify that the playlist being used cannot be anything but a certain filetype. In the case of the XML playlist above we would get an error using playlist.php even though the final output is actually XML. To solve this scenario you can add a rule to your .htaccess file like so:

Redirect /playlist.xml http://www.mydomain.com/playlist.php

Then simply use playlist.xml in the FlashVar and (fingers crossed) the PHP playlist should be referenced instead.

Share

Tumblr API CodeIgniter Library

Posted in PHP, Web Development on May 31st, 2011 by Steve Marks – 1 Comment

Tumblr API CodeIgniter Library

Over the past few years Tumblr has put up a good battle against other blogging platforms and still stands strong against the likes of WordPress and Blogger. Not wanting to be narrow-minded I decided to take a look into Tumblr and was actually very impressed. I don’t think I would consider using it myself (yet) but it’s clean layout and ease of use will definitely keep me checking back once in a while.

Whilst playing with the Tumblr interface I noticed they provide a pretty nifty API that allows developers to read, create, edit and delete posts from a users blog. Already being a massive fan of the PHP framework CodeIgniter, and a potential Tumblr convert, I decided to take up the challenge of writing a CodeIgniter library that easily allows these Tumblr API calls to be made through the framework. And so I give you first release…

Downloading and Installing the Library

You can download the Tumblr API library from the following location:

Download Library

View GitHub Repository

Within the ZIP there is a config file containing various authentication and display settings, and the library itself. These should be placed into ‘application/config’ and ‘application/libraries’ respectively.

Using the Library

Using the library is relatively straight-forward with most actions only taking a few lines of code. I will provide more in-depth documentation very soon but for now let’s take a look at a few examples. The Tumblr API documentation may also help a little.

Reading Posts

The tumblr.php config file in the ‘application/config’ directory:

// URL of tumblr blog.
// Replace to be the URL of the blog you want to read posts from
$config['tumblr_blog_url'] = 'http://[YOU].tumblr.com';

The tumblr.php library file in the ‘application/libraries’ directory:

// Load the library
$this->load->library('tumblr');

// Obtain an array of posts from the specified blog
// See the config file for a list of settings available
$posts = $this->tumblr->read_posts();

// Output the posts
print_r($posts);

Example output:

Array
(
   [0] => Array
   (
      [title] => This is a sample post title
      [body] => <p>And this is the body</p>
      [id] => 6010787147
      [url] => http://[YOU].tumblr.com/post/6010787147
      [url-with-slug] => http://[YOU].tumblr.com/post/6010787147/post-1
      [type] => regular
      [date-gmt] => 2011-05-30 20:41:17 GMT
      [date] => Mon, 30 May 2011 16:41:17
      [unix-timestamp] => 1306788077
      [format] => html
      [reblog-key] => Wfd5YDHP
      [slug] => post-1
   )
   [1] => Array
   (
      [title] => And another post
      [body] => <p>More lovely post content</p>
      [id] => 6011797127
      [url] => http://[YOU].tumblr.com/post/6011797127
      [url-with-slug] => http://[YOU].tumblr.com/post/6011797127/post-2
      [type] => regular
      [date-gmt] => 2011-05-29 20:43:17 GMT
      [date] => Sun, 29 May 2011 16:43:17
      [unix-timestamp] => 1306788077
      [format] => html
      [reblog-key] => Wfd4XDVP
      [slug] => post-2
   )
)

Adding New Posts

The tumblr.php config file in the ‘application/config’ directory:

// Email address and Password used to log in to Tumblr.
$config['tumblr_email'] = '[YOUR-EMAIL]';
$config['tumblr_password'] = '[YOUR-PASSWORD]';

The tumblr.php library file in the ‘application/libraries’ directory:

// Load the library
$this->load->library('tumblr');

// Add the post
$post_data = array();
$post_data['type'] = 'regular';
$post_data['title'] = 'This is a post created through the API';
$post_data['body'] = 'And this is the body';
$post_id = $this->tumblr->write_post($post_data);

// Output the newly created post ID
echo $post_id;

Editing Existing Posts

The tumblr.php config file in the ‘application/config’ directory:

// Email address and Password used to log in to Tumblr.
$config['tumblr_email'] = '[YOUR-EMAIL]';
$config['tumblr_password'] = '[YOUR-PASSWORD]';

The tumblr.php library file in the ‘application/libraries’ directory:

// Load the library
$this->load->library('tumblr');

// Add the post
$post_data = array();
$post_data['post-id'] = '6010787147'; // The ID of the post that we want to edit
$post_data['type'] = 'regular';
$post_data['title'] = 'This is an editing post updated through the API';
$post_data['body'] = 'And even an updated body';
$this->tumblr->write_post($post_data);

Deleting Posts

The tumblr.php config file in the ‘application/config’ directory:

// Email address and Password used to log in to Tumblr.
$config['tumblr_email'] = '[YOUR-EMAIL]';
$config['tumblr_password'] = '[YOUR-PASSWORD]';

The tumblr.php library file in the ‘application/libraries’ directory:

// Load the library
$this->load->library('tumblr');

// Delete the post
$this->tumblr->delete_post('6010787147');

I will be adding more examples and documentation very soon so be sure to check back. Alternatively please leave a comment if you have any questions or feedback about the library.

Share

Converting a PHP Array to a Query String… And Back Again

Posted in PHP, Web Development on May 18th, 2011 by Steve Marks – Be the first to comment

This is a scenario I have found myself in many times before; needing to convert a PHP array to a query string for use in a URL or POST request, and vice versa. Today I will discuss both methods and how they can be achieved with the aid of two very useful PHP functions; http_build_query() and parse_str().

Generating a URL query string from a PHP array

For the first part of this post let us take a look at the following PHP array:

$myArray = array(
	"car"=>"ford",
	"animal"=>"elephant",
	"language"=>"php"
);

Simple enough right? Just three elements in a single-dimension array. Now lets take a look at how we can convert this to a query string using our first function http_build_query():

echo http_build_query($myArray);

// Outputs: car=ford&animal=elephant&language=php

How easy was that! The function also works with multi-dimensional arrays as shown below:

$myArray = array(
	"car"=>array("ford", "vauxhall", "dodge"),
	"animal"=>"elephant",
	"language"=>"php"
);

echo http_build_query($myArray);

// Outputs: car[0]=ford&car[1]=vauxhall&car[2]=dodge&animal=elephant&language=php

We can get as simple or as complex as we like but I’ll let you play around with the function to get it working for you. Pretty useful stuff I think you’ll agree?!? Now lets look at the opposite effect of turning our query strings back into an array.

Creating a PHP array based on a query string

For this i want to refer back to the query string we generated in our first example. If you’ve forgotten it looks a little like this:

car=ford&animal=elephant&language=php

It’s time to welcome our second function of today, parse_str(). Let’s put it in into action:

$queryString = "car=ford&animal=elephant&language=php";

parse_str($queryString, $output);

print_r($output);

If done right the output will be a PHP array called $output (note the second parameter we used) containing three elements. We can see this below:

Array
(
    [car] => ford
    [animal] => elephant
    [language] => php
)

So there we have it. In just a couple of lines we’ve gone from an array, to a query string, and back to an array again.

Share

CodeIgniter MailChimp 1.3 API Library

Posted in PHP, Web Development on May 15th, 2011 by Steve Marks – 2 Comments

CodeIgniter MailChimp 1.3 API Library

There are lots of email marketing applications out there nowadays but by far my favourite is MailChimp. Alongside its strong use of AJAX to build an easy-to-use interface and its witty banter displayed throughout, it also has a great API allowing third parties to integrate with MailChimp accounts through simple POST requests.

By using the existing class provided by MailChimp I have now amended it so that it can be easily referenced through the PHP framework CodeIgniter by way of a new library.

Downloading and Installing the Library

You can download the library from the following location:

Download Library

View GitHub Repository

Within the ZIP there is a config file containing your MailChimp API key and the library itself. These should be placed into ‘application/config’ and ‘application/libraries’ respectively.

Your API key can be obtained by logging into your MailChimp account and navigating to ‘API Keys & Info’.

Using the Library

To use the library I recommend that you first get a good understanding of the MailChimp API itself. You can find the documentation for this at the following URL:

View the MailChimp API Documentation

Without going into every single method (that would take days) I have included just a few of the more common scenarios below to show how the MailChimp API and CodeIgniter can be used together:

Outputting lists:

$this->load->library('mcapi');

$retval = $this->mcapi->lists();

if ($this->mcapi->errorCode){

	echo "Unable to load lists()!";
	echo "\n\tCode=".$this->mcapi->errorCode;
	echo "\n\tMsg=".$this->mcapi->errorMessage."\n";

}else{

	echo "Lists that matched:".$retval['total']."\n";
	echo "Lists returned:".sizeof($retval['data'])."\n";

	foreach ($retval['data'] as $list){
		echo "Id = ".$list['id']." - ".$list['name']."\n";
		echo "Web_id = ".$list['web_id']."\n";
		echo "\tSub = ".$list['stats']['member_count'];
		echo "\tUnsub=".$list['stats']['unsubscribe_count'];
		echo "\tCleaned=".$list['stats']['cleaned_count']."\n";
	}

}

Subscribing an email address:

$this->load->library('mcapi');

$listID = "XXXXX"; // obtained by calling lists();
$emailAddress = "email@address.com";
$retval = $this->mcapi->listSubscribe($listID, $emailAddress);

if ($this->mcapi->errorCode){

	echo "Unable to subscribe email using listSubscribe()!";
	echo "\n\tCode=".$this->mcapi->errorCode;
	echo "\n\tMsg=".$this->mcapi->errorMessage."\n";

}else{

	echo $emailAddress." added successfully\n";

}

Disclaimer: Please note that I did not write the class to calling the MailChimp API. Credit for this should go to the MailChimp developers. I have simply modified it to work within the CodeIgniter framework.

Share

Using PHP to Capitalize a Word or Sentence

Posted in PHP, Web Development on May 15th, 2011 by Steve Marks – Be the first to comment

If you’re the webmaster of a site that gathers user’s information you’ll probably know all too well that user input can be, to put it blutently, a bit sloppy. This isn’t a problem as such, but can look a bit improper when this information is shared or displayed to other users.

Aside from spelling mistakes and unnecessary whitespace, another common trend I see is people either entering data in all lowercase or uppercase letters. As a result, and to help formalize this user contributed information, today I wanted to discuss how we can correctly capitalize a word or sentence using a couple of PHP functions.

The ucwords() PHP Function

The primary PHP function we’ll be using is ucwords(). The ucwords() function converts the first character of each word in a string to uppercase. Lets take a look at it in action:

$str = "this is the sentence to capitalize";
echo ucwords($str);

// Outputs: This Is The Sentence To Capitalize

OK great, the first letter of every word is now a capital. This is fine, however let’s take a look at the following scenario:

$str = "THIS IS THE SENTENCE TO CAPITALIZE";
echo ucwords($str);

// Outputs: THIS IS THE SENTENCE TO CAPITALIZE

Not what you expected? Let me explain… The ucwords() function only amends the first letter of every word and doesn’t touch the rest of the letters. Let me introduce the second function that we need to get this to work successfully; strtolower().

Using both functions together we can convert the entire string to lower case first, then capitalize it after. I’ve included an example below to demonstrate this:

$str = "THIS IS THE SENTENCE TO CAPITALIZE";
echo ucwords(strtolower($str));

// Outputs: This Is The Sentence To Capitalize

Now that’s more like it!

NB: Be careful when performing the above updates to user’s input. If a word should infact be lower case or uppercase, contains a hyphen (-) or is made up of initials you might be presented with the incorrect results.

Share

Echoing New Lines in JavaScript Alert Box Using PHP

Posted in Javascript / jQuery, PHP, Web Development on May 5th, 2011 by Steve Marks – Be the first to comment

Alert boxes in JavaScript provide a useful way to show the user an error, message or prompt. Adding new lines to one of these alert boxes can be done like so:

alert("This is line one\nThis is line two");

The above bit of JavaScript would output the following:

Reproducing With PHP

At first glance your initial thought on outputting the above using PHP might be to do something as follows:

echo "alert('This is line one\nThis is line two');";

Go ahead, give it a go and you’ll see that the new line is infact ignored and actually results in an error being generated.

The Solution

Solving this is easier than you might think. Simply add a second backslash before the existing one as shown below:

echo "alert('This is line one\\nThis is line two');";

Voila:

Share

Converting PHP print_r() Output to a String Variable

Posted in PHP, Web Development on April 4th, 2011 by Steve Marks – 2 Comments

The PHP function print_r() is great at outputting a variable in a human-readable format. What if we don’t want it to print to the screen however and instead, for example, want to include it’s output in an email?

The Solution

You might be suprised to learn that you don’t need to find another function or do any fancy output buffering to acheive this (I found this out the hard way!). The print_r() function supports a second parameter that, if set as TRUE will store the results to a variable rather than output them. A simple example would be like so:

$myArray = array('one', 'two', 'three');
$myString = print_r($myArray, TRUE);
echo $myString;

The above would then output the following:

Array
(
	[0] => one
	[1] => two
	[2] => three
)

Share

Removing Output From a cURL Transfer in PHP

Posted in PHP, Web Development on February 9th, 2011 by Steve Marks – Be the first to comment

Whether telnetting, performing FTP actions or getting a webpage’s content, cURL provides a very simple way to communicate with other servers over a wide array of protocols. PHP incorporates functionality to assist with using cURL making it easy to carry out tasks with just a few lines of code.

A problem I ran early into early on when writing my first script using cURL was that the output from the call was being output directly to the screen. Let’s take the following example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://username:password@ipaddress:port");
curl_setopt($ch, CURLOPT_QUOTE, array("DELE /images/house.gif"));
curl_exec($ch);
curl_close($ch);

When ran the above snippet will connect to a server via FTP and delete the required file, in this case ‘house.gif’. The code itself works fine and does exactly as expected, however following execution I then get a load of output to the screen like so:

drwxr-x--- 2 root root 0 Feb 8 05:47 . drwxr-x--- 2 root root 0 Feb 8 05:47 .. drwxr-x--- 1 root root 698 Feb 6 19:10 images -rwxr-x--- 2 root root 0 Feb 6 19:02 index.html

The Solution

That output is all well and good and actually provides some useful information, however what if we don’t want it blurted out the screen? Well, it’s easy. Simply add the following line of code to your cURL session:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

In doing this the transfer from cURL will now be returned as a string rather than output directly. Our final code now looks like so:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://username:password@ipaddress:port");
curl_setopt($ch, CURLOPT_QUOTE, array("DELE /images/house.gif"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch); // assign the return string to $output
curl_close($ch);

Share

PHP date() Function Showing Date from 1970

Posted in PHP, Web Development on December 30th, 2010 by Steve Marks – 3 Comments

I’ve lost count of the amount of times I’ve used the PHP date() function and wondered why it’s returning a date from 1970 so I wanted to share with you the most common reason/mistake I’ve found for causing this in the event that you are facing the same problem.

The Solution

The date() function can accept two parameters; the format of the required date and an optional UNIX timestamp. If passing the second timestamp parameter remember that it must be converted to a timestamp. This can be done using the PHP strtotime() function. Let me show you an example below of my usual error with the date being pulled from a database and a corrected working version.

echo date("d F Y", $row['my_date']);
// Incorrect: Outputs '01 January 1970'

echo date("d F Y", strtotime($row['my_date']));
// Correct: Outputs the expected date. eg '30 December 2010'

Share

Resolving the CodeIgniter “No Input File Specified” Error

Posted in PHP, Web Development on November 16th, 2010 by Steve Marks – 5 Comments

A site that I work with that is built on the CodeIgniter framework today started showing the error “No Input File Specified” when visiting any page other than the homepage. The cause wasn’t immediately available as I’d never seen this error before. It also wasn’t your average PHP error so I had to dig a bit further. After a while I came across a possible solution that, after trying, seemed to do the trick.

The Solution

The error wasn’t in my actual code (that’s what a developer likes to hear!), but was rather to do with the .htaccess file for my site. I’ve included below the part of my .htaccess file I had to change to get this to work correctly:

Before

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

After

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Spot the difference? Note the question mark following ‘index.php’ in the second snippet. In adding this my site now worked as expected. Why this changed randomly I’ll never know but I hope this helps if you find yourself in the same situation.

Share