24
Jul

SimpleMail - Easily send email’s with attachments from php.

Here is a pretty simple class that uses the default mail function so no sockets or direct connections to server’s
have to be used. But this script will allow you to add multiple contacts, as well as multiple attachments, easily.

It is as simple as this.

<?php
    include "SimpleMail.php";
    $mail = new SimpleMail("test@domain.com", "test@test.com", "This is a test message");

    $msg = "This is a quick test message, just sending some attachments\n";
    $msg.= "with this test email, yeah";

    $mail->AddMessage($msg);
    $mail->AddAttachment("test.txt");
    $mail->AddAttachment("test.png");
    $mail->AddAttachment("test.jpg");

    if($mail->SendMessage()) {
        echo "Your message was sussecfully sent";
    }
    else {
        echo "Your message failed to send, please try again later";
    }
?>

Hope someone finds it useful, enjoy.
SimpleMail (2)

23
Jul

Create image preview of textfile with PHP and the GD library.

This will be a small tutorial on how to create preview images / thumbnails of textfiles using PHP and the built-in GD library.
Note: This tutorial requires that you have GD2+ with Freetype support.

Ok so lets get started. This is actually quite an easy task, the basic idea is that we read in the lines of the
textfile convert tabs to spaces, and then draw each line to the image file we have created, easy huh?

First things first lets create the function name and arguments.

function FileToThumb($textSource, $thumbDest, $width, $height, $useEntireFile) {

}

Ok we now have are function and are ready to start adding code, but first a brief overview of
what each argument is for.

$textSource - The textfile to read from.
$thumbDesc - The path to save the image, use null to display in browser.
$width - The width of the image.
$height - The height of the image.
$useEntireFile - Use the entire file for the preview or just the first few lines.

Now that we have got that out of the way, lets start adding are code.
Firstly we will want to check a couple of arguments, as well as checking for are
fontfile.

if(file_exists($textSource) && is_readable($textSource) && file_exists("arial.ttf")) {
        if($useEntireFile)
            $fontSize = 4;
        else
            $fontSize = 7;

Ok that will check that the text file and font file exists as well ad checking whether of not
the text file is readable.

Now we can load are text file, get the maximum number of lines to draw
and set up are image and colors.

$lines = file($textSource);
$lineHeight = ($fontSize + 2);
$maxLines = ($height / $lineHeight);

$thumb = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($thumb, 0, 0, 0);
$white = imagecolorallocate($thumb, 255, 255, 255);
imagefill($thumb, 0, 0, $white);

Ok now all that is left is to draw the lines and save the image.

for($i = 1; $i < $maxLines + 1; $i++) {
            $line = str_replace("\t", "    ", $lines[$i]);
            imagettftext($thumb, $fontSize, 0, 2, ($i * $lineHeight), $black, "arial.ttf", $line);
        }

        if(!imagepng($thumb, $thumbDest)) {
            return false;
        }
        return true;

Ok and there it is, I used png because png is the better format for save images which contain alot of text.
But now you probaly want the whole thing, so here you go.

<?php
/*
    FileToThumb - Creates a thumbnail preview of a textfile.
    arg1 = textfile to create preview of.
    arg2 = destination of thumbnail preview. (Use null to display to browser)
    arg3 = width of thumbnail.
    arg4 = height of thumbnail.
    arg5 = true or false for using the entire file or the first few
        lines for the thumbnail.
*/

function FileToThumb($textSource, $thumbDest, $width, $height, $useEntireFile) {
    if(file_exists($textSource) && is_readable($textSource) && file_exists("arial.ttf")) {
        if($useEntireFile)
            $fontSize = 4;
        else
            $fontSize = 7;

        $lines = file($textSource);
        $lineHeight = ($fontSize + 2);
        $maxLines = ($height / $lineHeight);

        $thumb = imagecreatetruecolor($width, $height);
        $black = imagecolorallocate($thumb, 0, 0, 0);
        $white = imagecolorallocate($thumb, 255, 255, 255);
        imagefill($thumb, 0, 0, $white);

        for($i = 1; $i < $maxLines + 1; $i++) {
            $line = str_replace("\t", "    ", $lines[$i]);
            imagettftext($thumb, $fontSize, 0, 2, ($i * $lineHeight), $black, "arial.ttf", $line);
        }

        if(!imagepng($thumb, $thumbDest)) {
            return false;
        }
        return true;
    }
}
?>

Here is a simple example of the output of the function using this statment.

FileToThumb("test.txt", "test.png", 80, 120, false);

test

There is your ready to use function for creating image previews of textfiles, enjoy.

08
Jul

Simple Fuzzy Search with PHP

Approximate string search or Fuzzy string search, can be a difficult task if you have a very sophisticated searching / matching algorithm. So today I will show you a quite simple Fuzzy string search and use it to create a small efficient search application.

The CompareStrings method that we have ready is what we check a word against our search and give us back a value of difference (or threshold) from our search and the word we are checking. It does this by first checking each character while also checking for case insensitive or not, any difference in case if it applies or the character will add one to the threshold. We then check the length and add one for each single character difference in length. After all that we return the threshold and from there we can check the threshold to see if the word is something we want to keep and do something with. So before we do anything else, lets take a look at the CompareStrings function / method.

function CompareStrings($str1, $str2, $caseInsensitive = false) {
	$threshold = 0;

	if(strlen($str1) != strlen($str2)) {
		if(strlen($str1) > strlen($str2)) {
			$threshold = strlen($str1) - strlen($str2);
		}
		else if(strlen($str2) > strlen($str1)) {
			$threshold = strlen($str2) - strlen($str1);
		}
	}

	for($i = 0; $i < strlen($str1); $i++) {
		if($i <= strlen($str2) - 1) {
			if($caseInsensitive) {
				if(strtolower($str1{$i}) != strtolower($str2{$i})) {
					$threshold++;
				}
			}
			else {
				if($str1{$i} != $str2{$i}) {
					$threshold++;
				}
			}
		}
	}
	return $threshold;
}

So you can now see how it checks words, it’s not really difficult but also could be much more intelligent. So now lets start with our search method, “PreformSearch”. This will be a simple method that just checks the threshold and if it is within are acceptable limits we will store the word in an array, after we have sorted through the entire string we then return the array.

First lets set up the method and it’s arguments, as well as are array to store are matches.

function PreformSearch($search, $string, $threshold = 1, $caseSensitive = false) {
	$matches = array();
}

Ok we have that now lets start adding some searching abilities into are new function / method.
We are going to check that the string to search is actually a string and is longer then 0 characters.

if(isset($string) &amp;&amp; strlen($string) > 0) {

}
return $matches;

Now that is out of the way, we can now break up the string, loop though it and check for are matches.

$words = explode(" ", $this->string);

foreach($words as $word) {
        if(CompareStrings($search, $word, $caseInsensitive) <= $threshold) {
                $matches[] = $word;
        }
}

There, that is all that is needed, so lets see the whole thing all together.

function PreformSearch($search, $threshold = 1, $caseSensitive = false) {
	$matches = array();

	if(isset($this->string) &amp;&amp; strlen($this->string) > 0) {
		$words = explode(" ", $this->string);

		foreach($words as $word) {
			if(CompareStrings($search, $word, $caseInsensitive) <= $threshold) {
                                $matches[] = $word;
                        }
		}
	}
	return $matches;
}

and there it is. That is all that is needed for a very simple fuzzy string search using PHP.
So as you can see the above functions give you a base to start a much more sophisticated search then what is seen
here.

Below is a download to a FuzzySearch class, and a couple of test’s using it.

Fuzzy Search for PHP (7)

07
Jul

SpellChecker.

I am currently in the process of writing my own spell checking library, pretty much just because it’s a good learning experince and because I can. Anyway it seems to work pretty good so far, it is quite simple though uses the following steps to accomplish spell checking.

  1. Check current word in dictionary/list of words.
  2. If no exact match is found(case insensitive or not) then it starts matching.
  3. Matching the words involves going though each word in list and comparing the strings.
  4. Strings are compared by a CompateStrings method that rates string2 against string1 on a 100 point scale.
  5. Words that come withing a certain point limit of string1 will be added to a list of possible suggestions and returned.

This all seems to work pretty good, quite quickly for how it does it, but then I have not done any 10,000+ word dictionary / list searches yet, but I will soon and update with some speed results.

But back to the CompareStrings method, this method gives both strings 100 points, and rates string2 against string1 it first gets how many points each char are worth, afterwards compares each char in string1 to string2 a certain points per char are lost for each character that does not match, afterwards it checkers for the lengths and then multiplies the points per char to the difference in chars and returns the score that string2 got. Pretty simple, but pretty effective so far.

Anyways I will post a downlod to the current version quite soon, I have still got to implement a couple of things, maybe also make suggestion searches a little better.

05
Jul

NotificationBar - Free .NET control.

So I got a free control here for you. It is a pretty simple control, completly in C#. It is a notification/information bar, like that found in IE when you try to download something.

NotificationBar Example.Screenshot of notification bar and demo under linux.

Features of this control include.

  • LGPL License.
  • Easy to use.
  • Works on Mono.
  • Automatically resizes to fit text.
  • Can play system sound when shown.
  • Can flash control any number of times for any number of milliseconds.
  • Can show a ContextMenuStrip when clicked.
  • Useful for when you don’t want to show a MessageBox but want to give the user some info.
  • Uses .NET 2.0.
  • Written in C#.

It comes with a demo project and you can download it here - NotificationBar (165)

03
Jul

Hello world!

Well, here is my first post on my new blog / site (Code for thought).

So to get started, my name is Cory. I like to write code, dabble in electronics and mostly anythng that has to do with computers. On this blog in future posts you will find things such as C#/.NET code as well as controls for .NET. You may also find some PHP, C/C++, as well as just other random topics.

So welcome and hopefully you’ll come back later for more.