Posts Tagged ‘PHP’

No require with autoload

2. January 2011

No Comments »

If you have ever worked with a PHP framework you probably have noticed some features that allow you to develop code more rapidly. In this blog, I am going to address autoloading.

Traditionally, in object oriented PHP, we create a new source file for each class. If we want to create an object of a class, we have to include the php file using require_once (or using a similar function). If we do not include the source file, we will be issued a fatal error.

Fatal error: Class 'User' not found in ...

Lets say we have a User class defined as follows in a User.php file

<?php

class User {
    function __construct() {
        echo "Hello, World!";
    }
}
?>

If we want to create a new User object we would include user.php and use the new keyword to instantiate the class.

<?php
require_once('user.php');
$user = new User();

This is method reasonable for a small number of classes. However, large frameworks can span hundreds of classes, and having to write require_once for each class becomes a huge annoyance. PHP5 introduced an autoload magic method which is automatically called if the class source file cannot be found. The __autoload function takes a single parameter – the class being instantiated. If our class name corresponds to its file name we can do something as simple as:

<?php
function __autoload($class) {
    require_once($class . ".php");
}

Now, each time you instantiate a class, the autoload function will be automatically ran and it will automagically require your class. This is great, however all classes have to be in the same directory as the callee, and any decent framework uses a class hierarchy and spreads classes out into different directories. When I was writing my framework a few years ago, I stumbled upon a pretty awesome use of the autoload function. I think the idea was borrowed from the Zend framework. In a nutshell, the class names would correspond to their location on the file system. For example, the Zend framework has a class named Zend_Controller_Action_HelperBroker, and the class path Zend/Controller/Action/HelperBroker.php. What does this mean? With some additional code in our autoload function, we can convert the class name into its respective path allowing use to create a class hierarchy on our file system.

<?php
function __autoload($class) {
    $file = str_replace("_", "/", $class);
    require_once($file . ".php");
}

Now, with the onset of PHP5.3 and the introduction of namespaces, this method has been kind of depreciated for a more pragmatic method. Instead of naming our classes with really long names that correspond to their path, we can use a namespace instead. Thus our autoload function would look like:

<?php
function __autoload($class) {
    $file = str_replace("\\", "/", $class);
    require_once($file . ".php");
}

In my next blog, I will talk more about namespaces and give a better demo on how this is used.

Sending Text Messages in PHP

7. August 2010

3 Comments »

Recently I’ve had to implement an alert system in PHP were the alerts are sent via a text message. The concept is very simple – use an email to SMS gateway. Essentially, you send an email to a phone companies gateway server, that server then relays the email to the phone number specified via a SMS. Since PHP has the ability to send emails, the whole process is quite easy.

1. First you need to acquire a list of SMS gateways you are going to support. For an extensive list, check out Wikipedias List of SMS Gateways. For this tutorial, I will only be using AT&T Wireless (number@txt.att.net) and Verison (number@vtext.com).

2. Create a simple HTML form.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"></meta>
	<title>SMS</title>
</head>

<body>
	<form action="POST">

		<label for="provider">Provider: </label>
		<select>
			<option value="txt.att.net">AT&T Wireless</option>
			<option value="vtext.com">Verizon</option>
		</select><br />

		<label for="number">Number: </label>
		<input type="number" /><br />

		<label for="subject">Subject: </label>
		<input type="subject" /><br />

		<label for="message">Message: </label>
		<input type="message" /><br />

		<input type="submit" />

	</form>

</body>

</html>

3. Add the necessary PHP code to send the email

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"></meta>
	<title>SMS</title>
</head>

<body>
	<?php
		if(!empty($_POST['number'])) {
			mail($_POST['number'] . $_POST['provider'], $_POST['subject'], $_POST['message']);
        }
	?>

	<form action="POST">

		<label for="provider">Provider: </label>
		<select>
			<option value="@txt.att.net">AT&T Wireless</option>
			<option value="@vtext.com">Verizon</option>
		</select><br />

		<label for="number">Number: </label>
		<input type="number" /><br />

		<label for="subject">Subject: </label>
		<input type="subject" /><br />

		<label for="message">Message: </label>
		<input type="message" /><br />

		<input type="submit" />

	</form>

</body>

</html>

You will want to do some better error checking and validation, but thats it!

Basic OCR

4. January 2010

3 Comments »

This is a very basic optical character recognition script written in PHP. This is untested and serves merely a proof of concept. As noted in the comments, adjusting the sample size can improve results, since with a large sample size on a small image there can be many collisions. A database is needed to compare output results of this script with known values.

<?php

/* create a test image */
$im = @imagecreate(100, 20) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 1, 5, 5,  "Hello, World!", $text_color);

/***
 * Assumptions:
 *   A monochrome image where characters are black
 *   A single character is connected
 *   Characters are disjointed by white space
 */

$width = imagesx($im);
$height = imagesy($im);

/***
 * Notes:
 *   The smaller the sample size the more accurate it will be,
 *   however, it will take longer. Larger images can use a larger
 *   sample size wihtout compromizing much accuracy.
 */
$x_sample = 1;
$y_sample = 1;

$last = 0;
for($i = 0; $i < $width; $i++) {
    $col = array();

    for($j = 0; $j < $height; $j++) {
        $col[$j] = imagecolorat($im, $i, $j);
    }

    if(($current = array_sum($col)) > 0) {
        if($last == 0) {
            $l = 0;
        }

        for($k = 0; $k < $height; $k++) {
            if(($l % $x_sample) == 0) {
                if(($k % $y_sample) == 0) {
                    $sample .= $col[$k];
                }
            }
        }

        $l++;
        $last = $current;
    } else {
        $last = 0;
    }

    if(!empty($sample) && $last == 0) {
        echo $sample . "\n";
        $sample = "";
    }
}
?>

Output (each line represents a character)

00000011111100000000000000001000000000000000000010000000000000000011111100000000
00000000011000000000000000001011000000000000000011010000000000000000010100000000
000000100001000000000000001111110000000000000000000100000000
000000100001000000000000001111110000000000000000000100000000
00000000011000000000000000001001000000000000000010010000000000000000011000000000
000000000001000000000000000001100000000000000000010000000000
00000011111100000000000000000110000000000000000001100000000000000011111100000000
00000000011000000000000000001001000000000000000010010000000000000000011000000000
00000000111100000000000000000100000000000000000010000000000000000000010000000000
000000100001000000000000001111110000000000000000000100000000
00000000011000000000000000001001000000000000000010100000000000000011111100000000
00000001110100000000