:: Archive for the 'Web Development' Category ::

InputValidator – Simple Input Validation for PHP

Posted on December 26th, 2011 in PHP, Web Development by Greg

I recently needed a library for validating form input and everything seemed either verbose or required a huge number of files and libraries to be included. Here’s what I was looking for:

  • Easy to include in projects without having to change include paths, mess with auto loaders, or include other frameworks
  • Something that minimized the amount of validation code that needed to be written, preferably with a fluent interface
  • Ability to generate error messages that can be shown to the end user
  • Ability to transform data to data types needed by the rest of the script
  • Capability to validate against arbitrary regexes
  • Capability to validate against closures or other external functions

I couldn’t find exactly what I was looking for, so I decided to write it myself. I added the result, InputValidator, to my gUtils collection of PHP classes on Github. InputValidator is a standalone script for validating user input from forms or other sources.

Everything is in a single file, making it easy to include in any (PHP 5.3+) project. Here’s some example usage:

<?
require('gUtils/InputValidator.php');
// this could be from $_POST
$data = array(
  'name' => 'Greg Neustaetter',
  'email' => 'greg@emailaddress.com',
  'website' => 'http://www.gregphoto.net',
  'favoriteNumber' => 'xyz',
  'date' => '11/11/2011'
);
 
// pass in the data to be validated
$v = new gUtils\InputValidator($data);
 
// validate each field
$v->field('name')->required()->length(3,50);
$v->field('email', 'Email Address')->required()->email();
$v->field('website')->url();
$v->field('favoriteNumber', 'Your favorite number')->intRange(0,100)->toInt();
$v->field('date')->toDateTime('m/d/Y')->after(time()); // after the current time
 
if(!$v->allValid()) {
    echo '<pre>';
    print_r($v->getErrors()); // returns an array of errors indexed by field
    echo '<pre>';
    exit();
} 
$data = $v->getValues();  // returns an array of values indexed by field
$name = $v->get('name'); // get the value of name
echo $v->escape('name'); // escape the value of name for output with htmlspecialchars

This script would print the following error array:

Array(
    'favoriteNumber' => Your favorite number must be an integer between 0 and 100
    'date' => Date cannot be before 12/24/2011
)

In addition to validation the library includes a few filters to manipulate data and cast it to formats needed by your code. Take a look at the documentation on the Github wiki for a list of the 20 validators and the 8 filters.

Let me know if you find it useful or if you have any feedback…


Playing mp3s with SoundManager 2

Posted on November 23rd, 2008 in Music, Web Development by Greg

My friend Michael Ross is a musician and he sent me an email with a couple of the songs he recorded recently. I asked him if he would like me to put together a simple web page for his songs so that he didn’t have to send out emails with large attachments, and a week or so later we had a new site up and running for him – www.michaelrossmusic.net. He wanted a page that listed the albums, had links to download mp3 songs, and a way for people to listen to the songs without downloading them. I had used SoundManager 2 previously to have mp3s play on a page, so I knew that it would be a good fit.

I wanted to be able to build a simple page with regular links to the mp3 files and for JavaScript to do the magic of making the songs playable in the browser – this post explains how I made it happen. SoundManager 2 is a JavaScript library built on top of Flash – the music plays through Flash (which has much better audio support than browsers), but everything is controlled via JavaScript. I also used Prototype as a framework to build out the functionality.

Here’s what I did:

  1. Created a simple page with links to mp3 files
  2. Added a SoundManager handler so that as soon as it loads it instantiates PagePlayer, a JavaScript class I created
  3. PagePlayer takes a CSS selector as input (and optionally an options object) and identifies all of the links that match the selector – ‘a.mp3Link’ in this case (all links with the class ‘mp3Link’).
  4. For each of the identified links, PagePlayer creates a SoundManager sound object using the link to the mp3, adds a play button just prior to the song link, creates event handlers for the play button and sound object, and stores the song in a hash
  5. The event handlers take care of all of the logic: playing songs, making sure that only a single song is playing, changing the state of the button from play to stop

Here’s a current snapshot of the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
PagePlayer = Class.create({
	songCount: 0,
	songs: new Hash(),
	nowPlaying: null,
	options: null,
 
	initialize: function(selector, options) {
		this.options = {
			imgPath: 'images/',
			imgPlay: 'control_play.png',
			imgStop: 'control_stop.png',
			mp3LinkTitle: 'Download song'
		};
		Object.extend(this.options, options || {});
		$$(selector).each(this.addSong,this);
	},
 
	addSong: function(mp3Link) {
		mp3Link.title = this.options.mp3LinkTitle;
		var songId = mp3Link.identify();
		var soundObj = soundManager.createSound({
			id: songId,
			url: mp3Link.href,
			onfinish: this.finishHandler.bind(this,songId)
		});
		var controlBtn = new Element('img',{
			src: this.options.imgPath + this.options.imgPlay,
			className: 'audioControl'
		});
		mp3Link.insert({before: controlBtn});
		controlBtn.observe('click', this.toggleHandler.bind(this,songId));
 
		this.songs.set(songId, {
			controlBtn: controlBtn,
			soundObj: soundObj
		});
 
		this.songCount++;
	},
 
	toggleHandler: function(songId) {
		var oldSong = this.nowPlaying;
		var newSong = this.songs.get(songId);
 
		if(oldSong) {
			oldSong.soundObj.stop();
			oldSong.controlBtn.src = this.options.imgPath + this.options.imgPlay;
			if(oldSong === newSong) {
				this.nowPlaying = null;
				return;
			}
		}
 
		newSong.controlBtn.src = this.options.imgPath + this.options.imgStop;
		newSong.soundObj.play();
		this.nowPlaying = newSong;
	},
 
	finishHandler: function() {
		this.nowPlaying.controlBtn.src = this.options.imgPath + this.options.imgPlay;
		this.nowPlaying = null;
	}
});

And on the page it is started up as follows:

1
2
3
4
5
6
7
8
<script src="js/soundmanager2-nodebug-jsmin.js"></script>
<script src="js/pagePlayer.js"></script>
<script>
	soundManager.url = '';
	soundManager.onload = function() {
		new PagePlayer('a.mp3Link');
	};
</script>

It’s not the prettiest code, but it gets the job done in 1.58 KB of code and works at least in recent versions of Firefox, IE, Safari, and Chrome. So, if you need to add some mp3s to a page, check out SoundManager 2 – it’s easy to use, well documented, and super flexible…

Yelp for the iPhone

Posted on December 3rd, 2007 in Web Development by Greg

I just put together my first simple website for my new toy – my iPhone. It is a simple iPhone-specific interface for Yelp, my favorite source for restaurant and other local reviews. They have a ton of reviews for just about every local restaurant so I find myself using it all the time to find new restaurants to go to or to find more info about restaurants I already know. I could access the website just fine already on my phone, but it was a bit crowded and difficult to navigate on a small screen, so I decided it take this as a challenge to build my first iPhone web interface.

And yes, I’m probably about the 58th person to build a Yelp interface for the iPhone, but I was looking for something I’d actually use and learn from!

Yelp provides a REST search API that allows you to pass in a location and a search term and they return a JSON object with a list of matching businesses, their ratings, and the business info. I used the Zend Framework and the Prototype JavaScript library to put it together. I could have done a pure JavaScript implementation using script hacks, but figured it’d be better to have the PHP code serve as a basic proxy for the Yelp web service.

Try it out!

Announcing Gregphoto_Image – a PHP5/GD2 Thumbnail Class

Posted on February 3rd, 2007 in PHP, Web Development by Greg

I put together a simple, lightweight PHP class for generating thumbnail images. The class is compatible with PHP5 and uses the GD2 extension (included by default with PHP5) to create JPEG, PNG, and GIF thumbnails. I’ve setup a Google Code project for it: Gregphoto_Image where you can checkout the source from SVN and file bugs.

The class has the following basic features:

  • Ability to read JPEG, PNG, or GIF images
  • Ability to output JPEG, PNG, or GIF images
  • 4 modes of thumbnail creation
    • MAX_HEIGHT – you specify a maximum height and the dimensions are calculated based off of the height
    • MAX_WIDTH – you specify a maximum width and the dimensions are calculated based off of the width
    • BEST_FIT – you specify a maximum height and width and the dimensions are calculated so that the thumbnail
      is as large as possible without exceeding the maximum height or width
    • EXACT – you specify a maximum height and width and these are directly used. Causes distortion if the
      chosen aspect ratio is different from the aspect ratio of the image
  • Renders/saves images in their input format by default, but allows changing the format. For example, input a GIF but output a PNG
  • Fully documented object oriented code
  • Fluent interface for creating thumbnails with a minimal amount of code

The class is licensed under the MIT license, which basically means it can be used and modified by anyone – for personal or commercial use.

You can Download it from the project page on Google Code. You can view examples of it running on my site – the examples are checked into SVN and can be viewed on the project site. You can also view the docs.

Example usage:

1
2
3
4
5
6
7
require('path/to/Gregphoto_Image.php');
$image = new Gregphoto_Image('path/to/sample/image.jpg');
$image->setMaxHeight(200);
$image->setMaxWidth(200);
$image->setJpegQuality(90);
$image->resize(Gregphoto_Image::BEST_FIT);
$image->showThumbnail();
1
2
$image = new Gregphoto_Image('../images/fan.jpg');
$image->setMaxHeight(200)->setJpegQuality(90)->resize()->showThumbnail();
1
2
3
4
5
6
7
8
require('path/to/Gregphoto_Image.php');
$image = new Gregphoto_Image('path/to/image.jpg');
$image->setMaxHeight(200);
$image->setMaxWidth(200);
$image->setJpegQuality(90);
$image->setOutputType(IMAGETYPE_PNG);
$image->resize(Gregphoto_Image::BEST_FIT);
$image->saveThumbnail('path/to/thumbnail.png');

Enjoy!

Creating an Accordian Widget Class with Prototype

Posted on August 30th, 2006 in Web Development by Greg

Overview

The following is an example of a simple reusable widget created using the Prototype JavaScript library. The widget is an ‘accordian’ – a widget composed of multiple sections, of which only one is open at a time. This type of widget is available in all sorts of applications, from Microsoft Outlook (circa Outlook 2000), to web applications, and more. In addition to showing off this simple widget, I’d like to walk through it to explain how it works and how to write something like this with Prototype. For all of Prototype’s greatness, there is certainly a lack of documentation that makes it a little bit difficult to get into.

Example

Take a look at the example page I put together showing a few examples of accordians and their capabilities. This article will explain how to put together the class that does this.

Explaination: Creating Reusable Classes

I’ll skip with going through the HTML – you can see that on the example page if you’re interested – it would be helpful in understanding the javaScript here. In this example I’ve used version 1.5.0_rc0 of Prototype. The first line of the accordian.js file has the following:

1
Accordian = Class.create();

Prototype’s Class.create() sets up Accordian as an object that can be instantiated. When the object is instantiated the ‘initialize’ method, its constructor, will be automatically called. You setup all of the methods within the object by defining its prototype – an object with properties and methods. This could be done in the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Accordian.prototype = {
	initialize: function(args) {
		// do something
	},
	sectionClicked: function(args) {
 
	},
	openSection: function(args) {
 
	},
	closeExistingSection: function(args) {
 
	}
}

This object could be instantiated in the following way:

1
var myAccordian = new Accordian(options);

Explanation: Writing the Constructor

The constructor needs to take two arguments – the ID of the element that contains the accordian and the type of entry that is used for the header of each section. The constructors main job is getting a list of all of the sections within the accordian and adds onClick event handlers to the headers so that clicking them will open the section. The constructor is shown below:

1
2
3
4
5
6
7
initialize: function(elem, clickableEntity) {
   this.container = $(elem);
   var headers = $$('#' + elem + ' .section ' + clickableEntity);
   headers.each(function(header) {
       Event.observe(header,'click',this.sectionClicked.bindAsEventListener(this));
   }.bind(this));
}

Now to explain what’s going on in the constructor:

  • The first line defines the function that expects two variables – the ID of the element that holds the accordian and the type of element that will serve as the header for a section.
  • The second line sets a class property, ‘container’, to the element passed in with variable ‘elem’. It uses Prototype’s $() function, which in this case is equivalent to document.getElementById()
  • The third line uses the very powerful $$() function that returns an array of all elements that match a given css query. In this case, the query might look like ‘#myAccordian .section h3′, which would return all h3 elements under an element with class ‘section’ under the element with ID ‘myAccordian’.
  • Lines 4-6 setup the event handlers that will be used when the user clicks the headers. This uses the each() function that Prototype adds to arrays in order to quickly loop through an array without using a for loop or creating a bunch of temporary variables. This function takes a function as an argument that will be applied as an iterator over the array. This use of this technique is similar to the foreach concept in PHP (foreach($headers as $header)) and other languages. Because functions are objects in JavaScript, we need to add a trick at the end of the each function defined within ‘each’ – we need to add ‘bind(this)’. This means that within the new function, the ‘this’ keyword will be bound to the Accordian object, not to the function itself.
  • Line 5 uses Prototype’s Event class to setup the observer – in this case it will bind the classes sectionClicked method to any click on the header elements. Similar to the binding needed on the function, the reference to the sectionClicked function is follwed by ‘bindAsEventListener(this)’, which means that inside the event handler, ‘this’ will refer to the Accordian object, not to the clicked header element.

Explanation: Writing the Event Handler

The function referenced as the event handler in the constructor is shown below:

1
2
3
  sectionClicked: function(event) {
   this.openSection(Event.element(event).parentNode);
}

Functions called as an event always get passed an event object. This function takes this event and uses the Prototype ‘Event’ class to get a handle on the parent node of the element that was clicked, the section itself. It then passes this as an argument to another method in this class – openSection.

Explanation: Opening a Section

This function if fairly straightfoward – it checks to see if the section being opened is already open, and if not, calls a function to close the open section, and finally opens the new section. It is shown below:

1
2
3
4
5
6
7
8
9
openSection: function(section) {
	var section = $(section);
	if(section.id != this.currentSection) {
		this.closeExistingSection();
		this.currentSection = section.id;
		var contents = document.getElementsByClassName('contents',section);
		contents[0].show();
	}
}
  • The function takes one argument, the section that is to be opened
  • The second line uses the $() function to get the DOM element. It is important to note that this function can either take the section ID as an argument or the actual section DOM node. The $() function adds this extra flexibility
  • The third line checks to see whether the ID of the section is the same as the currently open section. If it is, no other logic is performed. If it isn’t, the next few lines will open that section.
  • After line 4 calls a function to close the existing section, line 5 sets a class property ‘currentSection’ to the new section
  • Line 6 uses Prototype’s getElementsByClassName, passing the class (contents) and the element under which it should look (the new section). This returns an array of elements
  • Line 7 takes the first element with class contents (their should only be one), and uses Prototype’s show() function to show the element

Explanation: Closing a Section

This last function is the simplest of all – it checks to see whether there is an open section, and if so, it hides it.

1
2
3
4
5
6
closeExistingSection: function() {
	if(this.currentSection) {
		var contents = document.getElementsByClassName('contents',this.currentSection);
		contents[0].hide();
	}
}
  • The second line checks if the currentSection exists – it is only set after the first section has been opened
  • The third line uses the same technique as in the previous function – it uses getElementsByClassName to get the elements with class ‘section’
  • Finally, the hide function will hide this element so that the section is collapsed

The Final Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Accordian = Class.create();
Accordian.prototype = {
	initialize: function(elem, clickableEntity) {
		this.container = $(elem);
		var headers = $$('#' + elem + ' .section ' + clickableEntity);
		headers.each(function(header) {
			Event.observe(header,'click',this.sectionClicked.bindAsEventListener(this));
		}.bind(this));
	},
	sectionClicked: function(event) {
		this.openSection(Event.element(event).parentNode);
	},
	openSection: function(section) {
		var section = $(section);
		if(section.id != this.currentSection) {
			this.closeExistingSection();
			this.currentSection = section.id;
			var contents = document.getElementsByClassName('contents',section);
			contents[0].show();
		}
	},
	closeExistingSection: function() {
		if(this.currentSection) {
			var contents = document.getElementsByClassName('contents',this.currentSection);
			contents[0].hide();
		}
	}
}

Conclusion

Though this is a fairly simple example, I hope it helped to explain some of the features of the Prototype library and can get people kickstarted to writing classes with JavaScript. Most of it is very simple…if only there were some real documentation. The best source right now is probably Developer notes for prototype.js, which covers features up to Prototype 1.4. Another site with a compilation of links is http://www.prototypedoc.com/.

Go forth and rid the world of nasty IE5 style, unreadable, browser-sniffing, hackish, global-scope JavaScript!