Leading Zeros

If you’re familiar with the sprintf function, you may already know this or perhaps, just like for me, it will be a novelty.
I was looking for a fast way of adding leading zeros to a number determined on a loop, for example, I want to call 40 images dynamically and while I know that they follow this format for example image_XXX where the x’s are replaced by a number leaded by zeros if it’s smaller than 3 digits I had no easy way of adding those zeros.

I just dumbly assumed that the only way was checking the string length, and if it equalled to 1 add two leading zeros, if it equalled to 2 add just one and if it was 3 or bigger, don’t add any. That’s fast enough, and it can be done like this:

switch(strlen($number)){
   case '1': $number = "00".$number; break;
   case '2': $number = "0".$number; break;
   default: $number = $number;
}

But that’s taking up 5 lines of code just for that small formatting, and imagine the implications of the same example but on a 10 digit number. So I found you can do the following with the same result and in just one line of code:

sprintf("%03d",$number);

Enjoy!

Build from the bottom-up

This is more of a suggestion than a programming related article.

The fact is that a lot of developers and developer’s code I’ve come across in the past few years seem to be aimed at a high end idyllic and flawless user who will have a certain configuration, resolutions, browser and plugins available and will experience therefore the same as the developer intended. This is however usually not the case and creating a website that works for some users and not for others is wrong . I could say it’s counterproductive and that it will harm your image as a developer/designer/programmer/professional but it’s easier to just say it’s wrong.

The truth is that if your site becomes somewhat popular you will start to receive visitors from Internet Explorer, Firefox, Opera, Safari and some other browsers with totally different configurations that include non-flash-enabled users and non-javascript-enable users, users that don’t accept cookies, or those who don’t parse css. My point is that your site should remain browsable and work under all those different scenarios and to do that you just have to keep some simple rules in mind.

What I mean by this is you should design your site for the worst possible scenario and then add the good stuff keeping focused on the fact that it should still work in the worst case scenario. Lets say you want to use one of the multiple lightbox scripts available to show the full sized view of an image. You could set the action with javascript making javascript-less users unable to see the full sized image or you could link the image to the full size and then modify it with javascript.

All javascript calls should be done over a non-javascript code, meaning that if you want to send a form using AJAX you should first make the form work without it and then extend it’s functionality with javascript. This way it will still work for both js and js-less users.
It’s true that on 2008 the amount of users that had javascript enabled was over 95% of the total but that leaves a whole 5% of your users seeing some ugly version of your site and probably never coming back.

If you have a small website that has a couple of visitors per day that’s probably just not worth doing since you will only lose a few visitors per month but for bigger sites that get thousands of visitors per day the loss could be huge.

Thanks for reading.

Currency Exchange with PHP

I found out this little neat function today while searching for some currency converter or should I say currency rate grabber. What this function does is it performs a google search and since google’s calculator handles currency conversions pretty well and up to date in the rates it grabs the information from it with the use of a regular expression. To be honest I would’ve never though of this but when you think about it it’s more than obvious. Google provides a service that we are using when we could be abusing it!

Here’s the code, Enjoy!!

function exchangeRate( $amount, $currency, $exchangeIn )
{
    $googleQuery = $amount . ' ' . $currency . ' in ' . $exchangeIn;
    $googleQuery = urlEncode( $googleQuery );
    $askGoogle = file_get_contents('http://.google.com/search?q='.$googleQuery);
    $askGoogle = strip_tags( $askGoogle );
    $matches = array();
    if (preg_match("/Rates provided for information only - see disclaimer./i", $askGoogle)) {
        $matches = array();
        preg_match( '/= (([0-9]|.|,| )*)/', $askGoogle, $matches );
        return $matches[1] ? $matches[1] : false;
    }
    else {
        $status = 'google says no';
        return $status;
    }
}

echo exchangeRate( 1000, 'euro', 'dollars' );

Source

Aside from the currency converter this gave me the idea of a word translator using google and php, or perhaps definition of words with google define. The possibilities are cute impressive when you put your mind to it.

Comparing images with PHP + GD

Some time ago I, for some reason, stumbled upon a website that made the visitor choose the image that was duplicated as some sort of human recognition. I’ve always liked those types of captchas that are not your usual type the text in the image, but this particular one seemed breakable for me. I though, “Hey, I can do this!” and in fact I did.

I wrote a function that took two image url’s as it’s attributes and returned if they matched or not. In fact it returns a factor I named “Dissimilarity Index” since the higher the number, the less similar those images are.
For those who are still into basics of PHP this may be a little bit too much, but it’s worth reading if you’re interested.

First I’ll show you the function, the I will dissect it as usual, line by line, avoiding the most basic stuff that hopefully you already know.

function dissimilarityIndexCalculator($str_img_url,$str_match_url){
   //Try to make images from the urls, on fail return false.
   $img_source = @ImageCreateFromString(file_get_contents($str_img_url));
   $img_match  = @ImageCreateFromString(file_get_contents($str_match_url));
   if(!$img_source || !$img_match) return false;
   
   //Get image sizes.
   list($int_img_source_width, $int_img_source_height)  = getimagesize($str_img_url);
   list($int_img_match_width, $int_img_match_height)    = getimagesize($str_match_url);
   
   //Resample to 1px each
   $img_16source = imagecreatetruecolor(16,16);
   $img_16match  = imagecreatetruecolor(16,16);
   
   imagecopyresampled(  $img_16source,
                        $img_source,
                        0, 0, 0, 0, 16, 16,
                        $int_img_source_width,
                        $int_img_source_width
                      );
   imagecopyresampled(  $img_16match,
                        $img_match,
                        0, 0, 0, 0, 16, 16,
                        $int_img_match_width,
                        $int_img_match_width
                      );
   
    $difference = 0;
    for($x=0;$x<16;$x++){
    for($y=0;$y<16;$y++){

    //Get the color of the resulting image
    $arr_img_source_color[$x][$y] =
        imagecolorsforindex($img_16source,imagecolorat($img_16source,$x,$y));
    $arr_img_match_color[$x][$y]  =
        imagecolorsforindex($img_16match,imagecolorat($img_16match,$x,$y));

    //Calculate the index
    $difference  += abs($arr_img_source_color['red']   - $arr_img_match_color['red'])       +
                        abs($arr_img_source_color['green'] - $arr_img_match_color['green']) +
                        abs($arr_img_source_color['blue']  - $arr_img_match_color['blue']);
    }
    }
   
    $difference = $difference/256;
   
   //Return an array with the information
   $arr_return = array( "dissimilarityIndex" => $difference,
                        "sourceImage" => array( "url"         => $str_img_source,
                                                "width"       => $int_img_source_width,
                                                "height"      => $int_img_source_height,
                                                "colors"    => $arr_img_source_color
                                               ),
                        "matchImage"  => array(    "url"      => $str_img_match,
                                                "width"       => $int_img_match_width,
                                                "height"      => $int_img_match_height,
                                                "colors"    => $arr_img_match_color
                                               )
            );
   return $arr_return;
}

The function takes two attributes, the first one is the url of the first image from the comparison, named $str_img_url and the second one, which is in fact the url of the second image, called $str_match_url. An example call to this function would be dissimilarityIndex("imageOne.jpg","imageTwo.jpg"); and will return the following information inside an array:

array( "dissimilarityIndex" => "An index reflecting the combined color differences",
       "sourceImage" => array( "url"      => "First Image Url",
                               "width"    => "First Image Width",
                               "height"   => "First Image Height",
                               "colors" => "RGB values for each pixel in the 16x16 matrix"
                               ),
       "matchImage" => array( "url"       => "Second Image Url",
                               "width"    => "Second Image Width",
                               "height"   => "Second Image Height",
                               "colors" => "RGB values for each pixel in the 16x16 matrix"
                               )
            );

There’s a lot going on in this function but in a nutshell what I’ve done is assured the images existed, if they do, Copy and resize the image with re-sampling to 16 pixels. These pixels with any luck contains the average colour of that image and by calculating the sum of the subtraction of the three colour indexes of each pair of pixels from the first image and the ones from the second image we get a number from 0 to 765 (255+255+255) that will represent the dissimilarity.

Lets get started dissecting the code:

   $img_source = @ImageCreateFromString(file_get_contents($str_img_url));
   $img_match  = @ImageCreateFromString(file_get_contents($str_match_url));
   if(!$img_source || !$img_match) return false;

On these lines we are creating two image objects from the urls declared as the function attributes. the file_get_contents function when targeted to an image, will return a string that contains the data of the image. I chose this approach instead of building the image directly from the url since it appears that this is less resource hungry for the server. Then using ImageCreateFromString targeting the newly created string, it will translate the string back into an image object. The @ once again will hide any error messages from the function.

The third line is a conditional that in the even that any of the images failed to create will return false, ceasing the execution of the function. If there are no images, we can’t compare them can we?.

   list($int_img_source_width, $int_img_source_height)  = getimagesize($str_img_url);
   list($int_img_match_width, $int_img_match_height)    = getimagesize($str_match_url);

It’s self explanatory, the function getimagesize returns an array of information from which the first two elements contain the height and width of the image. By using list we can declare more than one variable at one time.

   $img_16source = imagecreatetruecolor(16,16);
   $img_16match  = imagecreatetruecolor(16,16);

We create the image objects (empty for now) that will contain the resized copy of the original ones.

   imagecopyresampled(  $img_16source,
                        $img_source,
                        0, 0, 0, 0, 16, 16,
                        $int_img_source_width,
                        $int_img_source_width
                      );
   imagecopyresampled(  $img_16match,
                        $img_match,
                        0, 0, 0, 0, 16, 16,
                        $int_img_match_width,
                        $int_img_match_width
                      );

This is where the magic happens, what we are saying is, “Resize the image from the original width/heigh to 16px, and store that copy on $img_16source“. So we now have a 16 pixel image representing the average colour for each of the images we want to compare. All we need to do is a simple calculation and we will have the index, but before that we need to get the colour from those pixel. We do so using the imagecolorsforindex function inside two nested loops.

    $difference = 0;
    for($x=0;$x<16;$x++){
    for($y=0;$y<16;$y++){

        //Get the color of the resulting image
        $arr_img_source_color[$x][$y] =
        imagecolorsforindex($img_16source,imagecolorat($img_16source,$x,$y));
        $arr_img_match_color[$x][$y]  =
        imagecolorsforindex($img_6match,imagecolorat($img_16match,$x,$y));

        //Calculate the index
        $difference  += abs($arr_img_source_color['red']   - $arr_img_match_color['red'])   +
                    abs($arr_img_source_color['green'] - $arr_img_match_color['green']) +
                    abs($arr_img_source_color['blue']  - $arr_img_match_color['blue']);
    }
    }
   
    $difference = $difference/256;

Last, we calculate the dissimilarity index by subtracting the red, green, and blue integer values of the source image with the one from the match image. For those who don’t know what RGB is, it stands for Red Green and Blue. Those values will be 0 for the lack of that particular colour and 255 for the maximum value of that colour. So by adding the absolute value of those subtraction, we have the index!!

Lets put it to the test by comparing a few images, the first image will be compared against the two other:

When comparing the first image against the first match, we got a result of [dissimilarityIndex] => 38.640625.
When comparing the first image against the second match, we got a result of [dissimilarityIndex] => 57.22265625.

Note that for comparing images with really similar colours, it may give inaccurate results. This was thought more like a way of finding a match between different images. Anyway it performs pretty well under most circumstances and will surely do the work. If you read this post right when it was written (not like anyone reads my blog) you might have seen an old version of this function that used a resize to 1px instead of 16px. The result for this improved version is a lot more accurate and even with slight modifications to a source image it finds the closest match.

Extracting a date from a string with PHP

Hopefully this will be the first of many posts in this category. I was answering a question in Stackoverflow today about extracting dates from twitted messages and after all the debate that went on about what the best procedure was I decided to write my own function that will do exactly that, extract the most complex date from a string. By most complex I mean that it will prioritize something like “May 2nd 2008” over “May 2nd“. The function, named extractDateFromString (why make it less intuitive) returns an array containing the part of the string it decided was the best date, a UNIX datestamp of that date and a formatted date using either a user provided format or the predefined one.

It has some flaws, like the way I say that if the string length of the string that returns a valid datestamp is longer than a previously matching string, it should replace the old one. This could lead to saturday replacing sunday for example, and none of those is more valid that the other. This problem could be solver by storing all of those in an array and showing them in order. But it’s out of context as far as I’m concerned, it’s entirely up to you to do it.

Keep in mind that since strtotime only parses English strings, we can’t take advantage of it for other languages. This means, that you will only be able to use this to parse English messages in search of valid dates.

<?php
function extractDateFromString($datestring,$format = "F j, Y"){
    $datestring     = strtolower($datestring);
    $arr_datestring = explode(" ",$datestring);

    for($b=0;$b<count($arr_datestring);$b++){
        for($i=0;$i<count($arr_datestring);$i++){
            $tmp = $arr_datestring;
            if($b==0)$tmp = implode(array_splice($tmp, $i), " ");
            if($b>0) $tmp = implode(array_splice($tmp, $i,-$b), " ");

            if(strtotime($tmp) !== false){
                if(empty($result) || strlen($tmp) > strlen($result)) $result = $tmp;
            }
        }
    }
    if(empty($result)) return 'No dates found';
   
    $result = array('string' => $result,
                    'unix'   => strtotime($result),
                   'date'    => date($format,strtotime($result))
            );
    return $result;
}
?>

Examples of the output given by the function to some strings follow:
Input: “I’m going to play croquet next Friday”
Output: Array ( [string] => "next friday" [unix] => 1276844400 [date] => "June 18, 2010" )

Input: “Gadzooks, is it 17th June already?”
Output: Array ( [string] => "17th june" [unix] => 1276758000 [date] => "June 17, 2010" )

Adding watermarks to images with PHP

After the brief introduction to creating images with GD and PHP done on Text to Image with PHP we will be creating a function that given two attributes will return the first image with the second one as a watermark. For those of you who don’t know what a watermark is, it’s a mark on an image that either states the author of it, or prevents a sample image from being used instead of purchasing it etc. Usually is some text repeated all across the main image, it can also be another image instead of text.

On this introduction post we will create a function called watermarkIt that will take one argument, in this case the source image and return the same image. This may sound stupid but it’s going to be quite interesting since we will be checking multiple things like integrity of the, file type and valid file name:

<?php
    function watermarkIt($str_src_img){
        $img_source = @ImageCreateFromString(file_get_contents($str_src_img));
        if($img_source !== false){
            echo "Broken or invalid image";
        }
    }
?>

The first thing we’ve done is try accessing the image at the route specified at $str_source_img, and if there is no image or it’s corrupt/invalid we will return an error message. By using ImageCreateFromString and file_get_contents combined to get the source image we don’t have to worry about the file type as long as it’s valid. Since we will be using this function to return an image on the fly, we don’t want text error messages so let’s deal with it:

<?php
    function watermarkIt($str_src_img){
    header('Content-Type: image/jpg');

    $str_error_message = "The image is corrupt";

        $img_source = @ImageCreateFromString(file_get_contents($str_src_img));
        if($img_source == false){
            $img_error = imagecreatetruecolor(200,30);
            $color_black = imagecolorallocate($img_error, 255, 255, 255);
            imagestring($img_error, 5, 10, 7, $str_error_message, $color_black);
        imagejpeg($img_error);
        imagedestroy($img_error);
        }
    }
?>

Well, that’s a step forward isn’t it? Right now, we check if the file we wanted to use as a source image is valid and if not, we create a 200px by 30px image containing the value of the $str_error_message variable. That way if we call the function to an invalid image, it will still return an image. This of course can be changed to anything you want, a blank image or a pre-set error image. In the meantime I want to explain some lines of the code. I will assume you have some basic php knowledge so I’ll avoid the most obvious ones.

 header('Content-Type: image/jpg');

This sets the content type of the script file to a jpg image. Meaning that we can call it like we did in the introduction to images with php like this <img src='http://yoursite.com/route_to_script.php' /> and it will show the image generated by it.

$img_source = @ImageCreateFromString(file_get_contents($str_src_img));

There’s a lot going on in this line! We are creating an image object called $img_source that will contain the image specified when we called the function. The @ will hide errors. The ImageCreateFromString function will create and image identifier from the image stream created, forgive the repetition, by the file_get_contents.

$img_error   = imagecreatetruecolor(200,30);
$color_black = imagecolorallocate($img_error, 255, 255, 255);
imagestring($img_error, 5, 10, 7, $str_error_message, $color_black);

Those three lines are only used if the image we provided is invalid, so we need to create a new one, and we called it $img_error. The imagecreatetruecolor function will create an image identifier just like the ImageCreateFromString function did before. The moment we create it, it has no colours associated to it, and has a size of 200px by 30px since those are the values we declared when we called it. The next line allocates a black colour to the $img_error image, meaning that it will be available for use. The attributes it takes are, image identifier, red, blue and green. imagestring($img_error, 5, 10, 7, $str_error_message, $color_black); The imagestring funtion will add a string of text to the image specified at the first attribute, with a font specified at the second attribute, located at 10 pixels from the left side and 7 pixels from the top. More information on this function here.

The last two lines create and destroy the image, meaning we will output the image on the first one and once the output is completed, we will destroy it.
Why would be destroy it? Because creating and modifying images with PHP takes memory of course and this function frees any memory associated with it.

We wanted this function to return the same image if everything else was correct so lets do it!:

<?php
    function watermarkIt($str_src_img){
    header('Content-Type: image/jpg');

    $str_error_message = "The image is corrupt";

        $img_source = @ImageCreateFromString(file_get_contents($str_src_img));
        if($img_source == false){
            $img_error = imagecreatetruecolor(200,30);
            $color_black = imagecolorallocate($img_error, 255, 255, 255);
       
            imagestring($img_error, 5, 10, 7, $str_error_message, $color_black);
        imagejpeg($img_error);
        imagedestroy($img_error);
        }else{
            $arr_src_img_data = getimagesize($str_source_img);
            $int_img_type_start = strpos($arr_src_img_data['mime'],"/")+1;
            $str_src_img_type = str_replace("image/","",$arr_src_img_data['mime']);
            $img_output = call_user_func("imagecreatefrom$str_src_img_type", $str_src_img);
       
       imagejpeg($img_output);
       imagedestroy($img_output);
        }
    }
?>

$arr_source_img_data is an array created by the getimagesize function that contains the file type, the image size, and some other interesting values. For us, we’ll be using the ‘mime’ element of that array which contains the file type. Unfortunately, the format of the string contains both the file type and the extension. Since we just want the extension for now we use the str_replace function to remove the unnecessary parts.

$img_output = call_user_func("imagecreatefrom$str_src_img_type", $str_src_img); This line prevents us from having to use conditionals for creating the image object depending on the file extension. Instead, we use the [cci lang='php']call_user_func[/php] function to dynamically call the appropriate function to create the image. We do this because it’s not the same to create an image from a jpg a gif or a png, they use different functions.

On the next part, we will start getting into the actual watermarking. I apologize for anyone who was disappointed by this, but we need to set a strong base for our code to be bulletproof.

Validation with PHP – Part 3 – Explaining the class

<?php
class validate{
  public function fieldValidate($field,$str_validate_rules){
  $this->int_errors = 0;

On these three lines we declare a new class called validate. It has a public function called fieldValidate that takes two attributes. The first one is the variable that contains the field data we want to validate and the second one is a string containing the rules we want to use for the validation. This function is in charge of calling the appropriate private functions that will do the actual validation. We provide a string, and this function extracts and processes the rules.

$this->int_errors is a variable that will contain the number of errors after the validation process is done. In future posts we will add custom error messages, for now, it’s just a binary situation. It either validates or it doesn’t, we don’t know which rule failed.

    if(strpos($str_validate_rules,',') == false){
      $arr_rules[0] = $str_validate_rules;
    }else{
      $arr_rules = explode(',',$str_validate_rules);
    }

These lines ensure that even if we provide only one rule, it will be stored on an array so the next part of the code works. It may be doable in a more efficient way, but mind that I’m coding this on the fly just to help you understand this. If there is more than one rule, they will be separated by commas, so what we do is store them in an array by using the explode function.

    foreach($arr_rules as $str_rule){
      if($str_rule == "required") if(!$this->checkEmpty($field))      $this->int_errors++;
      if($str_rule == "numeric")  if(!$this->checkIsNumeric($field))  $this->int_errors++;
      if($str_rule == "alpha")    if(!$this->checkIsAlpha($field))    $this->int_errors++;
      if(strpos($str_rule,"length") === 0){
        $int_min = substr($str_rule,7,strpos($str_rule,"to")-7);
        $int_max = substr($str_rule,strpos($str_rule,"to")+2,-1);
        if(!$this->checkLength($field,$int_max,$int_min))         $this->int_errors++;
      }
    }

This part of the code is very important. It’s a loop that will decide which functions to call and for each particular function which attributes to use. The format I’m using for setting multiple validation rules as the second attribute when calling the fieldValidate function is the following:

  • “validationRule” For rules with no arguments
  • “validationRule{argument}” For rules with one argument
  • “validationRule{argument_onetoargument_two}” For rules with two arguments

Once again, multiple validation rules will be separated by commas. The first three rules, (required, numeric and alpha) require no arguments and therefore can be declared on a single line. Those read something like this: “If the value of variable $str_rule is equal to this keyword then if it doesn’t pass the rule linked to this keyword increase the value of $this->int_errors by one.” On the other hand, the “length check requires two attributes so we need to extract them before we can call the checkLength function. To do so, we use the function substr to locate the keyword ‘to’ that works as a separator between those two arguments. If the function doesn’t return true, we increase the value of the error count on $int_errors.

  if($this->int_errors > 0) return false;
  return true;
  }

This basically means “If there the error count stored in $int_errors is higher than zero, return false!” otherwise, return true.
The following code consists in all the private functions that are available for the public fieldValidate function to call. Each of those private functions will return true or false depending on whether the data is correct or not. Those are self-explanatory but if you have any doubts feel free to comment asking about it.

  private function checkEmpty($field = null){
    if(!$field) return false;
  return true;  
  }
 
  private function checkLength($field,$int_max = 99,$int_min = 1){
    if(strlen($field) < $int_min || strlen($field) > $int_max) return false;
  return true;  
  }
 
  private function checkNumericValue($int_field,$int_max,$int_min){
    if($int_field < $int_min || $int_field > $int_max) return false;
  return true;  
  }
 
  private function checkIsNumeric($int_field){
    if(!is_numeric($int_field)) return false;
  return true;
  }
 
  private function checkIsAlpha($str_field){
    if(!preg_match("/^[a-zA-Z ]{1,}$/", $str_field)) return false;
  return true;  
  }
}

$validate = new validate;
if($validate->fieldValidate("test","required,length{2to6},alpha")) echo "valid field";
echo $validate->int_errors;

/*
The output of this will be "Valid field - 0" since "test" doesn't break any rules.
$int_errors is still 0 since we didn't break the rules!
*/

?>

Now, using this class we can validate a single field against multiple rules. On the next part of this series we will go on and introduce an error output system that will allow us to locate the point where the validation failed and show us a message explaining what happened. Then on further parts we will introduce the ability to choose the language of the messages and move those to a separate file that will something like a language file.

Stay tuned.

Validation with PHP – Part 2 – The Core

The previous post “Validation with PHP – Introduction” merely scratched the surface of what can be done in regards of validating data with PHP. In this part I will be creating a basic validation class that will include a more customizable version of what we seen in the previous post and extend it with another function.

Going back to our first example, we had a form that contained a text field in which the user had to specify his/her year of birth. The rules we used for validating that data were two: make sure that the data is numeric with the is_numeric() function and that it was between 1950 and 1985 with simple operators.

Today, our form has two new fields. One that asks for the users favourite colour and another one that asks for a telephone number without spaces or any other character. To validate those three fields we could create two other functions so we end up with one function that validates each particular case or we can elaborate the function we built on the previous post so that it can validate both the year of birth and the telephone number. As for the favourite colour, we will write another one.

Let me show you what I mean by elaborate the actual function:

<?php
function validateNumeric($int_field,$int_max = FALSE,$int_min = FALSE,){
  if(is_numeric($int_field)){
    if(!empty($int_min) && $int_field <= $int_min) return FALSE;
    if(!empty($int_max) && $int_field >= $int_max) return FALSE;
   
    return TRUE;
  }
  return FALSE;
}

$int_year  = 1980;
$int_phone = 622671864;

if(validateNumeric($int_year,1985,1950)) echo "The year is valid";
if(validateNumeric($int_phone))      echo "The phone is valid";
?>

The extended function allows you to specify a minimum and/or a maximum number as a validation rule. Note that when validating the $int_year variable we specify the maximum year as the first argument and the minimum year as the second argument but when validating the phone number we just ask the function to verify if it’s a number or not. I like to put the maximum value as the second argument, right before the minimum because I find it more often situations where you don’t really care about the minimum but you do about the maximum, this is strictly something personal so feel free to change the order if you believe it’s better for your particular case.

This is ok if we just had one type of validation rules, in this case numeric values within a given range but, as I mentioned at the beginning of the post, we also want to know the users favourite colour. Since validating a colour is a completely different matter and there are hundreds of different colours out there, all we are going to do is make sure that whatever the user enters contains only letters and maybe white-spaces for the possibility of something like “pale green” as an input. Once again we will be assuming that we already have the users input in variables called “$type_field“.

<?php
function validateAlphaStr($str_field, $int_max = 25, $int_min = 1,){
  $regex_alpha = "/^[a-zA-Z ]{".$int_min.",".$int_max."}$/";
  if (preg_match($regex_alpha, $str_field, $arr_matches))   return TRUE;
  return FALSE;
}

$str_field = "red";

if(validateAlphaStr($str_field)) echo "The colour is valid";
?>

Lets explain the code a little bit. We created another function called validateAlphaStr that takes three arguments. The first one is the data we want to validate, the second and third ones are the minimum and maximum number of characters for that data. Those two arguments are not mandatory and have default values just like on the previous function. That means that if we don’t specify them it will use those default values instead.

The validation is done through a regular expression using the preg_match function. In common words the regular expression reads:
This will match if the only thing on $str_field is a string made with lowercase and uppercase letters and white-spaces with a length ranging between $int_min and $int_max, all matches will be stored on an array called $arr_matches“.

This means that if we try to validate “pink” it will work but if we try to validate “colour name longer than twentyfive characters” or “red 2” it will fail. Note that we could make the very long colour name succeed if we specify the maximum length to a higher number.

Last thing we need to do is to place those functions inside a class so they can share private functions for common validations like length and duplicates.
And this is where the magic happens, we will be transitioning from individual calls to a validation function to multiple calls from a validation class, lets do this!
That means that in one single call we will be able to validate against multiple rules:

<?php
class validate{
  public function startValidate($field,$str_validate_rules){
  $this->int_errors = 0;
 
    if(strpos($str_validate_rules,',') == false){
      $arr_rules[0] = $str_validate_rules;
    }else{
      $arr_rules = explode(',',$str_validate_rules);
    }
   
    foreach($arr_rules as $str_rule){
      if($str_rule == "required") if(!$this->checkEmpty($field))    $this->int_errors++;
      if($str_rule == "numeric")  if(!$this->checkIsNumeric($field))  $this->int_errors++;
      if($str_rule == "alpha")  if(!$this->checkIsAlpha($field))  $this->int_errors++;
      if(strpos($str_rule,"length") === 0){
        $int_min = substr($str_rule,7,strpos($str_rule,"to")-7);
        $int_max = substr($str_rule,strpos($str_rule,"to")+2,-1);
        if(!$this->checkLength($field,$int_max,$int_min)) $this->int_errors++;
      }
    }
   
  if($this->error_count > 0) return false;
  return true;
  }

  private function checkEmpty($field = null){
    if(!$field) return false;
  return true;  
  }
 
  private function checkLength($field,$int_max = 99,$int_min = 1){
    if(strlen($field) < $int_min || strlen($field) > $int_max) return false;
  return true;  
  }
 
  private function checkNumericValue($int_field,$int_max,$int_min){
    if($int_field < $int_min || $int_field > $int_max) return false;
  return true;  
  }
 
  private function checkIsNumeric($int_field){
    if(!is_numeric($int_field)) return false;
  return true;
  }
 
  private function checkIsAlpha($str_field){
    if(!preg_match("/^[a-zA-Z ]{1,}$/", $str_field)) return false;
  return true;  
  }
}

$validate = new validate;
if($validate->startValidate("test","required,length{2to6},alpha")) echo "valid field";
echo $validate->int_errors;

/*
The output of this will be "Valid field - 0" since "test" doesn't break any rules.
$int_errors is still 0 since we didn't break the rules!
*/

?>

Don’t worry, I will explain this line by line on the next post.

Validation with PHP – Introduction

Validation doesn’t necessarily mean just form validation. We can also validate any variable, in fact any data against a set of rules. Whether the data passes or not those rules is what makes it valid or invalid. I will be making a series of posts explaining specific validation rules and extending those with multiple examples.
In the end, we will have a full featured form validation system with error messages, customization and a lot more features.

Today I will show you a very basic introduction to validation.
Lets say I have a form with only one field which asks the user his/her year of birth. To validate the user input we will run a function that will return TRUE if it’s valid and FALSE if it’s not valid. That will be it. We will be assuming that we already have the user input stored in a variable named $int_year.

<?php
function validateYear($int_year){
    if(is_numeric($int_year)){
        return TRUE;
    }
        return FALSE;
}

$int_year = 1987;
if(validateYear($int_year)) echo "It's valid";
?>

This will validate as correct and therefore output the success message since 1987 is a number.
Okay, I admit it. This example is overly simplified and does not need a custom function since is_numeric already provides the functionality we were after but you grasp the concept, so lets make it a little bit harder. Lets imagine that we only want to consider valid inputs, those who are between 1950 and 1985. The previous example will look like this:

<?php
function validateYear($int_year){
    if(is_numeric($int_year)){
        if($int_year > 1950 && $int_year < 1985){
            return TRUE;
        }
    }
    return FALSE;
}

$int_year = 1987;
if(validateYear($int_year)) echo "It's valid";
?>

This example will not validate as correct and therefore will not output the success message because, even though 1987 is a number (first condition), 1987 is not between 1950 and 1985 (second condition). If we changed the value of $int_year to 1980 for example, it will be perfectly valid.

Text to Image with PHP

If you have at least some experience with PHP you probably know that there are several image engines available for you to work with.
Today, I’ll be showing you a simple way of generating an image from a user provided string using the GD library. The goal of this code will be to generate a simple image with white background and black text centred inside of it.

I will be using my naming rules as seen at “Naming conventions and practices in PHP“.As time goes by I will be extending this code to provide additional functionality, but for now, lets get started:

<?php
    function textToImage($str_text = 'Default text'){

We open PHP tags and declare a new function called textToImage. This function takes one argument called $str_text, note that I prepended str_ to the variable name, so we know it should be a string. If no argument is provided when we call the function it will use it’s default value, in this case “Default text“.

    header ('Content-type: image/png');

    $int_image_width  = 200;
    $int_image_height = 20;
    $obj_image = imagecreate($int_image_width, $int_image_height);

Inside the function, we first specify that the document type is a png image. Keep in mind that you will not be able to write this function on a file and include that file into your code. This means that you will have a file specifically reserved for the textToImage function and will call it from the other files. I will get into that later. Afterwards, we specify the height and width of the image and create a new image with the imagecreate function.

    $color_black = imagecolorallocate($obj_image, 0, 0, 0);
    $color_white = imagecolorallocate($obj_image,255,255,255);

That right, you can’t use colors out-of-the-box with the gd library, you first need to declare a variable that will contain a colour identifier for the image object using the imagecolorallocate function and then use it when needed.

    $int_font_id = 1;
    $int_x       = 5;
    $int_y       = 3;
    imagestring($obj_image,$int_font_id,$int_x,$int_y,$str_text,$color_white);

The variable $int_font_id contains a font identifier from 1 to 5 (can be higher if you declared more fonts using the loadfont function), $int_x and $int_y are both coordinates of the upper left corner of the text, relative to the container image. This means that if the values of both variables are 0, the text will start at the top-left corner of the image.
The imagestring function, places the value of $str_text on the $obj_image image at the given X-Y coordinates and with the specified font.

    imagepng($obj_image);
    imagedestroy($obj_image);
}

Those two lines output the image and destroy the image object to free memory after it’s generated.
Last but not least you want to call the function to see it working, do that like this:

textToImage("Test string");
?>

If you want to specify the text variable from another file, you can change “Test string” to “$_GET['str_text']” and wherever you want to use that image, just do the following:

<img src='http://site.com/route/texToString.php?str_text=StringHere' />

Thus generating an image on the fly with the use of the simple php function we created together.

Naming conventions and practices in PHP

It’s inevitable that while programming we tend to use short names for variables, functions, classes etc and while this may seem harmless in the short run, it will dramatically slow down your work if you have to expand or modify that code afterwards. You will find variables that have non-descriptive names and end up spending your time trying to understand who they are and what they do.

A solution for this is establishing a set of rules for when you name variables and any other custom defined code. For example, let’s say I wan to define a function that will return me a random number between 1 and 10.  Here is the code I would do if I was just messing around and didn’t care about naming conventions and rules:

<?php
function random(){
    $x = rand(0,10);
    return $x;
}
echo random();
?>

Yes, the code works, and it’s fast and simple but keep in mind that this is an overly simplified example. Lets say I want to extend that function so that it returns a randomly chosen element of a given array. Following the same style as the previous example, the code would look something like this:

<?php
function random($att){
    $x = $att[rand(0,count($att)-1)];
    return $x;
}
$array = array('element1','element2','element3');
echo random($array);
?>

Once again, it works, of course it does. And you’ve written it so you have no problem understanding it. But if you, or someone else had to come along at some point and try to understand it they will surely lose some time, and this is just a small and very basic function, just imagine what could happen on a big scale project.

The rules I use for programming in PHP are very basic and I’m pretty sure that there are lots of other styles out there. You just need to find the one that suits you and you feel more comfortable working with. Keep in mind that at first it may slow you down, but in the long run you will be thankful. There are just a few of them:

  • Use camelCase for functions and classes: This means that the first word on the name will be all under-case and the following words will start with a capital. Note that I use no underscores here.
  • Use underscores for variables and variables only: This includes arrays too of course. Another little trick I use is to specify the data type of the variable if possible before the actual name. For example a variable that will contain a random number will be named $int_random. That way I can easily see that it’s a number, and it’s random! (This doesn’t lock down the data type of the variable at all, it’s merely descriptive).
  • Don’t re-use variable names if possible.

My approach to this function using my own rules would be the following:

<?php
    function randomElement($array){
        $int_array_top = count($array)-1;
        $int_random    = rand(0,$int_array_top);
        $element       = $array[$int_random];

        return $element;
    }
    $array = array('element1','element2','element3');
    echo randomElement($array);
?>

Now, anyone who reads the code can see at first glance that the function returns a random element from a given array. But not only that. They know that the random element is selected by a random number between zero and the number of elements in the given array minus one (Array elements start at 0).
It may look uglier than the previous example, but it’s cleaner and easier to understand and maintain.

For anyone concerned about performance issues, I believe there is virtually no difference whatsoever between the optimized example and the one preceding it. This makes your code understandable, maintainable, and readable – in the long run, that far outweighs any slight performance benefit.

Notepad++

Notepad++ is a must have for any programmer that wants a fast and efficient coding environment that will not be resource hungry and that provides lots of functionality. Personally I think that it’s aimed at non-compiled programming languages and particularly to web and web-based application development. I use it mostly when I work on html, php, xml, javascript and asp but it has syntax highlighting for lots of other languages aswell.

In essence, Np++ is a text editor on steroids. It has all the features that you will want, from code highlighting and multiple-selection of text to quick-texts and macros. Add to the list an incredible versatility in means of customization of the way the code you’re viewing is displayed, allowing you to change the colour of backgrounds and text as well as the font, size and style of these. Not to forget it’s free.

I’m not going to say that it’s the best solution for your particular case since there are countless options available at the time and some of them are incredible. For example, while coding in Php I’m sometimes drawn to Phped, for it’s code error highlighter. It’s good to be able to locate syntax errors without having to actually run the script on the server (we all hate those missing semi-colon or unexpected braces errors).

Most of the functionality is available out-of-the-box but for the ones that aren’t there are plenty of plugins at your disposal.

One of the functions I like the most or at least one of the most useful in my particular case, is the ability to compare different files using multiple views.  The following image shows how notepad looks with two separate views of a two documents while comparing them. Notice how each line that doesn’t match is highlighted and within that particular line, each dissimilarity is also highlighted. There is also a navigation bar which locates the differences for ease of access. Lines that don’t match are marked with an icon that will represent a general difference, an extra line, or a missing line. Those icons are easily recognizable and will make your experience even easier.

Screenshot of the comparison tool of Np++

Here is the link to their site and a direct link to the currently latest download:
- Site
- Download