Archive for the ‘PHP’ Category.

Apparatus (also Happy New Year!)

For a while now I’ve been working on a web-based PHP interpreter; an interface I can use to quickly test or develop code from my browser. Ultimately this resulted in Apparatus, an in-browser PHP read-evaulate-print loop. Give it a try: http://tinsology.net/scripts/apparatus/.

Note that this is currently a beta version. Any help with identifying bugs will be greatly appreciated.

P.S. Happy New Year!

PHP Iterators

If you’ve spent any significant amount of time coding in PHP you’re most likely familiar with PHP’s foreach loop syntax. In simple terms, a foreach loop is an easy way to iterate over the elements of an array. Chances are if you’re reading this you already know that. What you may not know, however, is that it is possible to iterate objects with a foreach loop. Assuming you have some collection class (an object that stores some number of elements in an organized manner) you can iterate over its elements just like you can the elements of an array.

$myCollection = new Collection(); //arbitrary collection class

foreach($myCollection as $element)
{
	//do something with $element
}

In order to do this however, you must design your class in such a way as to let PHP know that it supports iteration. As is the case with many other languages, you do this by implementing an interface. An interface is basically a class containing only abstract methods (constants are allowed as well). A class implementing a certain interface must provide the definitions for those abstract methods. The interface we need in this case is called Iterator and has 5 methods that must be implemented:

class MyIterator implements Iterator
{
	//Returns the current element
	function current()
	{

	}

	//Returns the current key (position in the iterator)
	function key()
	{

	}

	//Moves to the next element (returns void)
	function next()
	{

	}

	//Resets the iterator
	function rewind()
	{

	}

	/*Returns true of the current position in the
	   iterator exists. False otherwise */
	function valid()
	{

	}
}

From these methods you can derive that the underlying implementation of a PHP foreach loop is something like this:

$i = new MyIterator();

//make sure the iterator is in the starting position
$i->rewind();
while($i->valid())
{
	//get the current element and key
	$value = $i->current();
	$key = $i->key();

	//iterator to the next element
	$i->next();
}

//equivalent foreach loop
foreach($i as $key => $value)
{

}

Now that we know what the methods do it is time to implement them. The class we’ll implement will be a stripped down version of a linked list that supports only an add method (plus the iterator methods):

class LinkedList implements Iterator
{
	private $head;
	private $last;
	private $count;
	private $curr; //iterator counter
	private $currNode; //iterator position

	function __construct()
	{
		$this->head = null;
		$this->last = null;
		$this->count = 0;
		$this->curr = 0;
		$this->currNode = $this->head;
	}

	function add($v)
	{
		$newNode = new Node();
		$newNode->value = $v;

		if($this->head == null)
		{
			$this->head = $newNode;
			$this->last = $this->head;
		}
		else
		{
			$this->last->next = $newNode;
			$this->last = $this->last->next;
		}
		$this->count++;
	}

	function current()
	{
		echo "LinkedList::current \n";
		return $this->currNode->value;
	}

	function key()
	{
		echo "LinkedList::key \n";
		return $this->curr;
	}

	function next()
	{
		echo "LinkedList::next \n";
		$this->currNode = $this->currNode->next;
		$this->curr++;
	}

	function rewind()
	{
		echo "LinkedList::rewind \n";
		$this->currNode = $this->head;
	}

	function valid()
	{
		echo "LinkedList::valid \n";
		if($this->curr >= $this->count)
			return false;

		return true;
	}
}

class Node
{
	public $value;
	public $next;

	function __construct()
	{
		$this->value = null;
		$this->next = null;
	}
}

Notice that I’ve added an echo to each iterator method in the LinkedList class; I’ll explain why later. In case you’re unaware, a linked list is just a series of ‘nodes’. Each node contains a value and a reference to the next node in the list. This pseudo code demonstrates how to traverse a linked list, outputting the values as we go:

Node current := head;

while current != null
	print current->value
	current := current->next
endwhile

Since, however, our linked list class implements Iterator we can traverse it using a foreach loop:

$list = new LinkedList();
$list->add('a');
$list->add('b');
$list->add('c');

foreach($list as $key => $value)
{
	echo $key . ' : ' . $value . "\n";
}

Here is the output for the above code:

LinkedList::rewind
LinkedList::valid
LinkedList::current
LinkedList::key
0 : a
LinkedList::next
LinkedList::valid
LinkedList::current
LinkedList::key
1 : b
LinkedList::next
LinkedList::valid
LinkedList::current
LinkedList::key
2 : c
LinkedList::next
LinkedList::valid

The above shows the position and value of each element in our list, as well as the order each iterator method is called.

P.S.

This is the first part in a three part series. The next part will be published soon.

A Supplement

I’ve just added a section about session management to Creating a Secure Login System the Right Way.

Check it out

Easy PHP Search with Opera

If you use Opera you’re probably aware that it supports shortcuts in the address bar that allow you to run a search on various search engines and websites. For example, if I type g tinsology in the address bar, you’ll get the Google search results for the keyword tinsology. You can do similar things with yahoo, amazon, ask and other sites that come preconfigured in Opera.

Personally, I find myself frequently using this shortcut to Google PHP documentation. For example if I’m looking up documentation for the implode function, I’ll type g PHP implode. More often than not the first result is what I’m looking for and it is just a matter of waiting for the search results to load, clicking the first result, and waiting for the php.net page to load.

Ideally, however, I would want to be able to go directly from typing my search in the address bar to the php.net results page. It just so happens that Opera allows you to do this by adding a custom search engine. What we want to do is to be able to type p [my search] in the address bar. To begin we need to open the Search Preferences pane:

  • In Opera click Tools -> Preferences... or press Ctrl+F12
  • In the resulting window select the Search tab.
  • Click the Add... button.

In the add window there are three fields we are interested in: Name, Keyword, and Address (if you don’t see the address field click the details button). Name is just the name of this search shortcut; I named it PHP, but it doesn’t really matter what you name it. Keyword is the keyword you type in the address bar before your search query. For a Google search it is g. I chose p, but once again you can choose anything you’d like. Also, the keyword doesn’t have to be a single letter, for instance you could use php. The address field tells Opera what to do with your search query. Without explaining too much I’ll just say that the value we want to use is: http://us2.php.net/manual-lookup.php?pattern=%s. The %s token will be replaced by our search query. For instance typing p implode will cause Opera to open http://us2.php.net/manual-lookup.php?pattern=implode

That’s it; leave all of the remaining field blank. You can now use Opera’s address bar to instantly search the PHP documentation. You can use similar methods for running searches on other sites, the hardest part is finding the correct search URL (its even harder if the search query cannot be URL encoded, that’s when the Use Post option comes in handy).

Unlimited PHP Function Parameters

If you’ve ever used PHP’s library functions you’ve most likely noticed that several function such as array() can take an indeterminate number of arguments. Normally when defining a function you specify each argument in the function declaration. Obviously it would be impossible to define an infinite number of arguments in such a way. PHP does, however, allow you to accomplish this through the function func_get_args().

func_get_args() returns an array consisting of all of the arguments passed to a function. Using this method you can bypass the conventional method of defining parameters in the function definition all-together. Here is an example:

function add()
{
	$total = 0;
	$args = func_get_args();

	foreach($args as $arg)
	{
		if(is_numeric($arg))
			$total += $arg;
	}
	return $total;
}

echo add(1, 2, 3); //will return 6

If for whatever reason you need to know the total number of arguments passed to a function, PHP provides the func_num_args() function.

When retrieving arguments in this manner it is important to remember that func_get_args only returns an array of arguments passed by the user. It does not account for default values.

PHP Lorem Ipsum Generator

For the most up-to-date information regarding this script go to the PHP Lorem Ipsum page in the scripts section.

The other day I needed to populate a database with some placeholder content. Doing this manually was out of the question so I decided I’d find a text generator, specifically a Lorem Ipsum generator. For anyone unaware, Lorem Ipsum is non-sense, placeholder text used in publishing and design. It allows the developer to see their work completely populated with text, without having to actually create the text. Obviously, for this purpose, any kind of text generator would work to some extent, but traditionally Lorem Ipsum is used.

To get to the point, I successfully located several web-based generators, but no stand-alone PHP class or function. To be honest, I didn’t look too hard and someone a little more determined not to write any code most likely would have found it, but I decided to create my own PHP Lorem Ipsum generator. Here is a rundown of some of the features in the current version:

PHP Lorem Ipsum Generator
Version: 1.0
License: BSD

Download:
Link moved Here.

Features

  • Generates content in three modes: Plain, HTML (content blocks nested in <p> tags), and Text (plain text in paragraph form)
  • Sentences are punctuated and vary in length based on statistics collected here: http://hearle.nahoo.net/Academic/Maths/Sentence.html. Sentence length will vary on a Guassian distribution.
  • HTML output is ‘clean-code’ formatted with tabs and new lines rather than just blobs of code
  • More output formats to come…

Feel free to request additional features.

Usage

The only public method in the class is getContent.

Description
string getContent( int $wordCount [, string $format = html] [, boolean $loremipsum = true] )

Returns the desired amount of content as a string.

Parameters

wordCount
The number of words to be returned.

format
The output mode, one of ‘html’, ‘txt’, or ‘plain’. HTML by default.

  • HTML: The content is divided into paragraphs, using the paragraph ( <p></p> ) tag.
  • Text: The content is divided into paragraphs with the leading line of each paragraph tabbed
  • Plain: The content is returned unformatted

loremipsum
Whether or not the content should begin with ‘Lorem ipsum’. True by default.

Example

require('LoremIpsum.class.php');

$generator = new LoremIpsumGenerator;

//100 words in html format
$generator->getContent(100);

//100 words without any formatting
$generator->getContent(100, 'plain');

//100 words with 'text' formatting
$generator->getContent(100, 'txt');

//100 words with html format, not beginning with lorem ipsum
$generator->getContent(100, NULL, false);

//or
$generator->getContent(100, 'html', false);

Additional Notes
Both the HTML and Text output modes use paragraph formatting. The mean word count of each paragraph is predetermined and can be set in the constructor, currently the default is 100. Note that this is the mean word count, the actual word count for each paragraph will vary in the same way the length of each sentence will vary.

Changelog
Version 1.1 (Planned)

  • Additional output modes. List mode and possibly more

Version 1.0:

  • Initial Release

PHP: Complex Variables in Strings

If you are at all familiar with PHP you are probably aware that you can put variables inside double quotes. For example:

$x = 5;
echo "x is equal to $x";

The above code will output “x is equal to 5″. This method works fine with simple variables, but will fail with references to member variables of objects or arrays:

//will not work
echo "x is equal to $myObject->x";

//also won't work
echo "x is equal to $myArra['x']";

To avoid this problem, PHP allows you to use curly braces to seperate variables that need to be parsed:

//will work
echo "x is equal to {$myObject->x}";

This is also useful in situations where you want to output a variable in the middle of a word:

//will not work
$birthday = 16;
echo "My birthday is on the $birthdayth";

//will work
echo "My birthday is on the {$birthday}th";

Note that { cannot be escaped in a string. If { is followed by $ PHP will assume that you want to parse a variable. To get the literal {$ you must escape it like this:

echo "Curly brace followed by dollar sign: {\$";

//will output
//Curly brace followed by dollar sign: {$

Strings and Output in PHP

I’ve seen a lot of questions and false assumptions regarding strings and output. Here is a short review of some common questions:

print vs. echo

I often see people suggesting that others should use echo as opposed to print for performance reasons. While it is true that echo is faster than print, the difference is insignificant. The reason echo is faster is because print behaves like a function (even though it’s a language construct) and sets a return value. This being the case, there are some important differences between the two, and there are a few cases where you have to use print in place of echo.

As I mentioned, print behaves like a function. You can use it just as any other funciton call and it has a return value (always 1). Like print, echo is also a language contruct, but does not behave like a function. Here are some cases where print must be used in place of echo:

$b ? print "true" : print "false";
//with echo
function isOne($x)
{
	if($x == 1)
	{
		echo $x . ' = 1';
		return true;
	}
	else
	{
		echo $x . ' != 1';
		return false;
	}
}

//with print
function isOne($x)
{
	if($x == 1)
		return print($x . ' = 1');
	else
		return !print($x . ' != 1');
}

In the print implementation of isOne the speed difference between echo and print is negated.

Concatenated strings Vs. Multiple calls to echo

Is it faster to concatenate all of your output into a single string and then output it or is it faster to output your strings as you go? The answer is the former; concatenating strings is faster than doing output. Does this mean that you should cram all of your output into one string and output it at the end of your script? Not necessarily. Like the performance difference between print and echo, the performance difference here is almost always negligible. Use which ever method makes sense at the time. You should prefer to concatenate your output, but sometimes ‘output as you go’ makes for cleaner code which is more important in this case.

Double vs. Single quotes

PHP provides two different ways to encase strings: Double quotes and single quotes. There is an important difference between the two. If your string is encased in double quotes, you can place variables with in it like so:

$x = 5;

echo "x is equal to $x";

What this means is that PHP must parse the string, looking for any variables. Single quotes on the other hand are never parsed, meaning that if your string contains no variables it is preferable to use single quotes. Similar to the previous examples, the performance difference is minor; however, using double quotes for no apparent reason is just wasting runtime. Here are some good reasons to use double quotes:

$x = 5;
//your string contains a variable
echo "x = $x";
//your string contains single quotes
echo "Matt said, 'peanut butter is awesome'";

In the second case, it would be faster to escape your single quotes using \ but the performance difference is minor and using double quotes looks cleaner.

Output without echo (or print)

Print and echo are not the only ways to do output. At any point in your code you can close your PHP tags and start doing output as if it were normal HTML:

<?php
for($i = 0; $i < 10; $i++)
{
	?>
	<p>Hello</p>
	<?php
}
?>

This will output Hello, nested in paragraph tags, ten times. This method is useful when you have a large amount of output that you don’t want to have to worry about nesting in quotes. Personally, when using this method, I prefer to use PHP’s alternate control flow syntax:

<?php if($x == 10) : ?>
	<div>X is equal to 10</div>
<?php else : ?>
	<div>X is not equal to 10</div>
<?php endif; ?>

You can use this syntax with all of PHP’s control flow statements (ie while, if, for, foreach, switch, etc…).

Output Buffering

What should you do if you have a large string that needs to be manipulated? Normally if you had a very large string, such as a block of HTML, you could use the method I just described, however, doing it like that would output the string immediately. Using quotes is clumsy and unnecessary. The answer is to use an output buffer:

<?php
ob_start(); //start the output buffer
?>
<div>My Website</div>
<p>This is my website where I write about stuff and junk. Enjoy!<p>
<div class="footer">copyright 2009 tinsology.net</div>
<?php
$output = ob_get_clean();
echo str_replace('2009', '2010', $output);
?>

In the above example, ob_start() starts the output buffer. From this point on, any output, including output from print and echo, will be stored in the buffer. ob_get_clean() returns the output as a string and deletes the buffer content. PHP’s output control functions contain some very useful functionality, I highly recommend that you read the documentation carefully: PHP output control functions

Strings Are Arrays

I’ve seen a lot of people asking questions about how to find a certain character or sequence inside a string. It is common for people to turn to the library in order to find a function that does this for them, but it is likely the case that the answer is right in front of you. If you need to search thorough a string for whatever reason you can index it as an array. This is the case in a lot of language (PHP, C++, Java).

In a non-type-safe language like PHP people often forget the distinction between primitive types and other constructs. Primitives are often things like int, float, double, long, and char. Strings are generally not a primitive type but an array of chars. Most languages tend to hide this fact from you, because strings are so common it is often more convenient for the programmer to deal with them as if they were not an array of characters.  For example, Java does not support operator overloading; you can only use arithmetic operators (+, -, *) on primitive types, with the exception of strings, which can be appended using the + operator.

So how can you use this fact to your advantage? There are many cases where indexing strings rather than passing them to some function can serve your purpose more efficiently. Here are some examples in PHP:

Ex.
You have several lines of text and you want to count the instances of a particular word. One way to do this would be to use explode to turn the text into an array of words and then count the instances of that word:

$text = 'cat dog chicken cat bird mouse cat lizard';
$words = explode(' ' , $text);
$count = 0;
foreach($words as $word)
{
     if($word == 'cat')
          $count++;
}
echo $count; //should output 3

One function call and one loop, pretty simple right? Maybe not. It is important to remember that function calls may a lot more than they appear. In order to split the string into an array of words, explode must search through the string for a space. If all you need to do is count the number of instances of a word, there is no need to waste time constructing an array of words and then looping through that array. Here is a more efficient way:

$curr = '';
$count = 0;
$searchStr = 'cat';
$text = 'cat dog chicken cat bird mouse cat lizard';
$len = strlen($text);

for($i = 0; $i < $len; $i++)
{
     if($text[$i] == ' ')
     {
          if($curr == $searchStr)
               $count++;

          $curr = '';
     }
     else
          $curr .= $text[$i];
}

The above example contains several more lines of code, but it is important to remember that the number of lines in a program should not be used to measure the performance of a program.

Short Tags

The standard opening tag for php is <?php, however there are two alternative opening tags:

<? – short for <?php
<?= – short for <?php echo

Although they may be convenient, you should never use these tags. The main reason I don’t use them is because short tags can be disabled in the php.ini, so if your application relies on them, it will fail when this feature is disabled. Recently a couple of short tags crept into (by my own mistake) one of my applications and a user reported he was getting a parse error on the last line of code in the file. After looking over the code several times I replaced the short tags with the longer version and all was well.

If you are writing portable applications I recommend that you disable short tags in your own php.ini, so in the case that you place one by mistake (as I did) you will get the error message instead of one of your users reporting it weeks later.