Tag Archives: Programming

Profiling your PHP scripts (performance benchmark)

This is going to be a short post. I’m going to show you my profiling class and explain it block by block, then I’m going to stop typing and click the “Publish” button on the bottom right hand corner, capisci? Good.

A little summary – “What is profiling & performance benchmarking anyways?”
This provides a way for you to determine how “long” it takes for PHP to parse a script from start to finish and then returns the time (in microseconds) so that you can judge how “well” you’re writing your scripts.

The profiler() class

<?php
// profiler class
class profiler {
public $start_time;

function start() {
$t = microtime();
$time = explode (” “, $t);
$this->start_time = doubleval($time[0])+$time[1];
}

function finish() {
$t = microtime();
$time = explode (” “, $t);
$end_time = doubleval($time[0])+$time[1];
echo substr(sprintf (”%01.4f”, $end_time-$this->start_time), 0, 6);
}
}

// instantiate the class
$profile = new profiler;
$profile->start();
// code goes here to benchmark
$profile->finish();
?>

That’s the profiler() class. Now let’s break it down and see what it’s actually doing.

The start() function

function start() {

Store the current timestamp (in microseconds) into a variable for further reference (start the timer)

$t = microtime();

Take the microtime & the miliseconds (to the right) into an array (explode it)
$time = explode (” “, $t);

Fill the $start_time with the $t (microseconds) actual value (numbers only)
$this->start_time = doubleval($time[0])+$time[1];
}

The finish() function

function finish() {
Get the microtime again
$t = microtime();

You recognize this already
$time = explode (” “, $t);

You see it again
$end_time = doubleval($time[0])+$time[1];

Return the actual time subtracting this, from the actual $start_time (what we got from start())
sprintf returns a formatted string USING a format, in this case it’s %01.4f which says it’s a float (f)
and echo it.
echo substr(sprintf (”%01.4f”, $end_time-$this->start_time), 0, 5);
}

Now don’t get all smart on me and say “Yeah but how long does it take to run the profile class, because if you don’t know that then you..” shhh. It takes (I ran this) 0.0001 to 0.0002 seconds to run the profiler class.

The code for what I just said was simply this

$profile_profile = new profiler;
$profile_profile->start();
$profile = new profiler;
$profile->start();
$profile->finish();
$profile_profile->finish();

Which just tells you how long it takes to run it (you’re profiling your profiler)

So you can use this in all of your code to see how long it takes in microseconds (or full seconds) to run.
A couple of examples of benchmarked times (on an AMD K6-2 660MHz with 256MB PC100 RAM & 5400 RPM HD)

  • It took me 0.00010 seconds to run this while loop to echo a value and increment by 1
    $i = 0;
    while ($i <= 200) {
    echo $i . ‘<br />’;
    $i++;
    }

And that’s about it so if you’re any good at math you know that to run that loop 400 times it would take 0.00010.

This should help you judge your scripts quality & performance.

Hope this helps someone.

I eat styrofoam cups because I can’t,

bryan

Digg This

Data validation in PHP

Update: I have a new post that explains data sanitization.

One of the most important things to do in any PHP script or program, interface whatever it may be is to check the data and verify it’s what YOU want and not allow any spoofs. One of the biggest most common pitfalls newer programmers make (and for some reason, PHP programmers) is the lack of data validation. There is a known rule of program and it, simply put is:

NEVER TRUST USER SUBMITTED DATA – BAR NONE.

I get responses like “You’re too uptight about security” or “Yeah well then how’s the site supposed to work if you never take user submitted data?” Both can be true, but the latter is simple. Just check the data, what’s so friggin’ hard about that? The most commonly checked type of data seems to be an Email address with all of its quirks and workarounds it’s hard to verify whether or not an email address is real. Mind you data validation isn’t always just about malicious MySQL injection attemps or XSS (Cross site scripting) it can even be as simple as verifying a blog for bad links/language.

Usually I use pre-build functions (or class methods) to verify data integrity returning true/false for qiuck usability.

You don’t have to know Regex to be good at data validation but, you can’t really go very far without it. There are lot sof pre-built functions in PHP to verify what kind of content data is. Okay, enough talking, lets get to some code.

Here’s a few built-in PHP functions that can save you some time

  • ctype_digit() – checks for numeric characters like 123 etc
  • ctype_alpha() – checks for letters of the alphabet
  • ctype_xdigit() – checks for characters representing a hexadecimal digit
  • ctype_alnum()  – checks for alpha numeric characters

Some other built-in functions

  • is_array() – checks if a variable is an array
  • is_int() – checks if a variable is an integer
  • gettype() - returns the type of a variable
    Fore more of these functions go to php.net/is_int
    Also look at this page

For more of these functions, or any functions in general you can visit one of the most resourceful sites you’ll end up visiting php.net. I should also mention that if you haven’t read the PHP manual please do, they made it for a reason. It has almost everything you’ll ever need and if you’re running windows there is an awesome windows .CHM manual you can download that is searchable. It’s a great reference. Anyway, no more tangent.

These functions are built directly in to PHP so you don’t have to recode a lot of stuff, now, I will say, they don’t exactly do everything you want them to do, granted; but they’re a start.

Note – anytime you want to lookup a function just go to php.net/function to look it up. PHP automatically will return the corresponding page if there is one for that function/topic.

Anyways, back to data validation.

Like I said earlier, some things just aren’t built-in to PHP quite yet, like email validation, or content validation or whitespace checking. Regex (as it is commonly referred to) is a method in which you can check for literally any type of value.

I will write a followup article on Data validation with Regular Expressions in PHP after this one, I just thought people should know aside from writing their own data validation methods, PHP has a couple handy built-in functions.

require() or include() with PHP?

A lot of people mis-use these two functions. In short, the difference is this

  • require() “requires” a file to be “included” before it proceeds, if the “required” file is not found, script execution halts returning a fatal error.
  • include() “includes” a file if it can find it, if not, it returns a warning explaning why (usually just bad file name)

Which one is more important is really up to you, but I would by default recommend using include() over require() just less mess to deal with.

Extending the include functions
PHP added this cute functionality to the include functions called “_once”, so you could include_once() or require_once() a file. They both do the same thing they’ve always done with an exception, they only include a file once. Pretty hard to understand isn’t it? that require_once only requires a file once. Pretty original :) But seriously, this function used to save my life until I realized that it was simply bad design (most of the time) that caused the problems that “_once” functions were created to fix. In other words, If I’m including a file more than once anyways, I need to fix that problem instead of just being lazy and using PHP’s little include_once() speciality function. Now I’m not arguing that they made it, and it ships with PHP so they must still have it in circulation for a reason, yes, you’re correct.

Someone in ##php pointed out to me that although it might come in handy, every time you use include_once or require_once PHP has to look through the list of files already included and check their contents to make sure it hasn’t already included them. (read that again slowly.) Which narrows itself down to a lot of performance wasted because you were too busy to re-design your application a little bit to only include a file once. Think about it, you’re putting the statement there anyways, how hard is it to just make sure you aren’t duplicating it? I posted an article about duping your PHP code here, you should probably read it. It will help you with other things.

In closing, I use include() functions by default and require() if I REALLY need a file. Even then, I just use include(). So, now you know.

“Quotations” & Concatenation in PHP

So maybe you’ve seen people use single quotes, maybe double quotes? Personal preference? Wrong. Processing time? True. Also, you’ve seen them use this crazy “.” thing in between variables and strings, or maybe even entire functions?! Yes, that’s called concatenation. (con-cat-in-ation) yes, it’s a mouthful but it’s extremely useful.

“Quotations”
In PHP there are two types of quotations (actually 3 but I’ve never met anyone that uses the third, so, I’ll just tell you it’s the “ and unless you have some stupid infatuation with them, just use normal single or double quotes.)
The two types we are going to talk about in this article are

  1. Single quotations
  2. Double quotations

NOTE Sometimes they are referred to as, “unparsed quotations” and “parsed quotations” you’ll know why soon.
Single quotations (unparsed quotations) – ‘ ‘
In PHP single quotations can encapsule (hold) any type of data, numbers, decimal, strings, variables, it doesn’t matter. The difference here is when we feed it a variable to hold alongside a string or something, for example:
<?php
$name = ‘crainbandy’;
echo ‘what’s up, my name is $name’;
?>
Instead of actually saying “what’s up, my name is crainbandy” this will say, “what’s up, my name is $name” because single quotes turn a built-in PHP function called “variable parsing” off. Meaning, instead of looking for $variables to replace with their corresponding values, they just use the raw text which is $name in the case of the script above. Make sense? In other words… “Single quotes don’t replace variable names with their corresponding value.”

Double quotations (parsed quotations) – ” ”
This is the opposite of single quotations in the fact that, they replace variables with their corresponding value.
Example
<?php
$name = ‘crainbandy’;
echo ‘what’s up, my name is $name’;
?>
This will actually say, “what’s up, my name is crainbandy” instead of “what’s up, my name is $name“, the opposite result of single quotes.

The main thing I want you to get out of this is the fact that PHP has to turn on a lot of referencing and underlying matching if you use double quotations, whether or not there is a variable involved. You think PHP just somehow knows that a variable has a VARIABLE for a value? No. PHP has to look.

For example,
<?php
$name = “crainbandy”;
echo $name;
?>
Why in the world would you want to parse a solid string with double quotes when you could have just as easily used $name = ‘crainbandy’; instead and gotten the same result? How much processing time and performance you lose by things like this I’m not sure, but you do lose some obviously.

So now you know the difference. If I look at your code and I see variable assignments to solid values with double quotes I’m going to e-slap you.

In a nutshell, use single quotes! Unless for some reason you need to “parse” the strings, fine, but I still think you can use the next big word “concatenation” to get around that.

Concatenation (Or a period .)
This is such a cool feature, I don’t know where I would be in my scripts without it. As you can see in my Constantly use Constants in PHP article, when I’m defining constants I use a combination of single quotes with concatenation. It’s cool, check it out.

For example, usually to echo a variable value to anything you would have to use double quotes.
Example:
<?php
$name = ‘crainbandy’;
echo “what’s up my name is $name”;
?>
This would produce the desired effect right? Of course it would, but, there’s something more we can do with this simple script.

Concatenation! Concatenation simply means “Attaching a value to a variable” by means of… “concatenating” it.
Example
<?php
$name = ‘crainbandy’;
echo ‘what’s up, my name is ‘ . $name;
?>
You like that? You FREAKING like that? That’s what I thought. Yes, you’re observant. “What in the world is that backslash doing in there?” Well my friend. That is called “escaping strings” and this article is not about that. Sorry. Back to concatenation.

So there you have it, PHP actually knows that when you have a concatenated string like the one above, just continue going on replacing values/running methods and or functions until you reach that beautiful semi-colon. Why would you use this instead of the “time saver” that double quotes is? Well for several reasons

  1. You cannot use arrays values inside single quotes or double quotes (you can with double quotes, but you run into a problem)
  2. You can’t run functions or methods inside a double quoted or single quoted string. With concatenation, you can do that.

Running a function inside an echo statement with PHP
<?php
$name = ‘crainbandy’;
echo ‘what’s up, my name is ‘ . strtolower($name);
?>
You see how that works? Cool. Glad. Psyched. Riled. Sweet

Usually in your PHP scripts you will be using a mixture of single quoted, double quoted, and concatenation. Sometimes there’s just no reason to use concatenation and make yourself go through the extra typing, but, it usually is more resourceful.

One other way to concatenate strings is with the .= operator.

$name = ‘wax’;
$name .= ‘jelly’;
This creates a variable called $name that has the value “crainbandy”, pretty cool huh? Okay. Til next time…

Constantly use constants in PHP

I’m going to talk to you about a few ways to use PHP’s constants to save yourself a lot of time and hassle.

PHP has this cool thing called a “CONSTANT” that basically lets you define a string to represent a value that is available everywhere. it basically doesn’t have a variable scope.

Note: a constant cannot be an array. It can be anything else, just not an array.

Syntax
define(’CONSTANT_NAME’, ‘VALUE’);

In a nutshell, a constant can be useful for anything from the maximum amount of failed logins you allow before prompting for CAPTCHA or simply banning their IP temporarily.

For example, Instead of having to type crainbandy.com/link or if you’re linking a stylesheet like http://www.crainbandy.com/style.css, or anything you can just use a constant to represent it.

The good thing about using constants inside your scripts is that instead of changing your entire script to adjust URL changes or any type of change, you can just change the constant.

Compare the two pieces of code below:

<?php
include(’/crainbandy/header.template’);
include(’/crainbandy/navigation.template’);
include(’/crainbandy/body.template’);
include(’/crainbandy/secondary.template’);
include(’/crainbandy/footer.template’);
?>


Read more