PHP Error Handling and Debugging – Part 1

This article describes the process of testing PHP code.  Using the tips that I will explain can help to decrease the code/test cycle time.

The first thing that you must know in order to plan your code/test process is the environment in which your code will run.

If you have full control of the system, less configuration is required. In this case you can rely on the default settings, and simply need to know where the logs are kept by default. On a typical LAMP (apache) system you can find the log files in /var/log/httpd. Check the documentation for the operating system that you use as some operating systems use a different directory (i.e. one version of Ubuntu uses /var/log/apache2). By default error messages from php will be kept in this directory.

If you are developing on a server where you don’t have access to the default logs, you can configure where your log messages are sent by putting a php.ini file containing the directive

error_log: path_to_log

in the root of the domain.

With this information in mind, we can begin to find code errors.

There are two error types to look for:

  1. parse
  2. runtime

A parse error is the first thing to look for when testing new or modified code. This can be something like a missing semicolon or other grammatical mistake. If a parse error occurs, it will be sent to PHP’s error_log. A simple way to find this kind of error is to load the file directly in a browser (i.e. an AJAX script that would not normally run in a browser could be tested this way for parse errors). With a default PHP installation the parse error will shown on the screen.

Most errors that are encountered are runtime errors. There are two kinds of runtime errors:

  1. exception
  2. functional

The first kind of runtime error happens when a statement or function call that is grammatically correct encounters a unexpected circumstance such as an invalid parameter (i.e. fopen(file_that_doesnt_exist,’r’)). This kind of error can only be seen during an actual run of the code with valid inputs. Opening the file in the browser directly usually will not find it as the inputs will not be those that would typically be encountered. For example opening an AJAX script that relys on the _POST variable for its input will typically not run many of the branches because of the missing _POST variables. To find this error, run the script as it would typically be run and check the error log for errors.

A functional runtime error is when the code runs, doesn’t generate an error, but doesn’t produce the expected outputs. To find this error use one or more of the following techniques:

  • echo/printf
  • error_log
  • try/catch

The simplest way to find errors is by adding echo statements to the code. This method can be somewhat tedious and slower to use than others, but a few well placed echo statements that use print_r to show the value of key return data structures can sometimes quickly illuminate the source of the malfunctioning code. The problem with this method is that because it outputs directly to stdout (the web browser) it is only available if the script can be run in the web browser directly with typical inputs. Many times this is not possible (i.e. for AJAX or cron code).

A more general way of debugging is to use the error_log function instead of echo. With the error_log function you can direct the messages to a file of your choosing with

error_log($message,3,"path/filename")

or to the configured error_log mentioned earlier via

error_log($message)

A bonus when using the error_log() function is that you also get a timestamp for each error logged.

If a runtime error is expected, a try/catch statement should be placed to ignore it or otherwise handle it in a way that doesn’t cause the script to stop abruptly.  This way the script will continue to run and an error will be logged.  This is better because you will know at what section of code the error occurred.  If the blocking error had gone uncaught (in the case of AJAX responder script errors), the calling application might have received a malformed response (parse error).  A try/catch statement is only helpful when a blocking exception occurs, and will not help to debug functional runtime errors.  The structure of this type of code testing is as follows:

try {
 //your new code
 } catch(Exception $E) {
 error_log(E.getMessage());
 }

In this article we have discussed simple code/test cycle techniques for PHP.  Tune in next time for part 2 where we will review using a debugger such as XDebug.

Guidelines for writing great articles

Part of my efforts with the Mississippi Magic Magazine involve setting up guidelines for writing great articles.  If you are wondering why a technologies consultant is posting guidelines on writing great articles then let me explain.  We are in the business of creating success in our constituents that we partner with through consulting and development.  That being said… Mississippi Magic Magazine provides an outlet of expression for people and businesses in Mississippi but it does not employ writers to produce magazine content.  Therefore, all the writing done on the Mississippi Magic Magazine is done by volunteer writers that have a vested interest in the community.  From business owners to pastors of churches, people active in leadership in the community provide all of the content found in magazine.  To make this a profitable venture for each of them, we’ve found it necessary to publish a guidelines for writing great articles.

Benefits:

  • People like to do business with those they are familiar with.   Through connecting with our community through your articles, you’ll lower the barriers that people have to traditional broadcast style advertising communications.  .
  • Articles will be broadcasted to the RSS subscription readership.
  • Articles will be indexed by search engines so that anyone looking the information you provided will find it and you on the internet.
  • Articles will spread in a viral method through through social media sites such as twitter, facebook, and linked in.
  • Unlike traditional media, articles written will be available online well into the indefinite future.
  • Articles will link your thoughts, expertise, and methods to your perceived value as a solutions provider and allow people to reach you.
  • Articles always make the front page when they are published.
Good practices:
  • Offering needed information to make an informed decisions.
  • Offering solutions by showing how to solve a problem.
  • Providing lists of methods or resources.
  • Expounding upon a subject.
  • Offering information about events by featuring information, pictures, and video covering people in the community.
  • Praising and pointing out the good about others.
  • Simplifying complex information, instructions, or events.
Avoid:
  • Slandering others.
  • Defaming others.
  • Advertising your products or services.
  • Soliciting business.
Using these methods, community leaders can provide invaluable content that leads people in the community to them as a provider of services and goods.  Through the relationship formed between the reader and author in the magazine articles these leaders have an inroad to the reader when the reader seeks to find a provider for a need or want that the author can fulfill.
This style of marketing defined in these guidelines for writing great articles are known today as inbound marketing.  By using them you’ll get found on the internet and connect with your customer.
– Joel

Flattening the org chart with mobile web technology – part one the pyramid.

Part one – The traditional pyramid organizational structure

When I was in college (10 years ago!) studying information technology and business one of the hot topics was how information technologies would flatten the pyramid organizational chart of many businesses. Ten years later after graduating and participating in management in several organizations as a corporate citizen of the of the business world I can say that I’ve seen little progress. Many organizations seemingly have invested in new technologies only to primarily use email systems to communicate with most of the information moving from top down with the majority of the decision support technology being leveraged at the top of organizations and not the bottom.

Traditional businesses are built upon a pyramid structure of management that works on a one to many relationship between the highest level leader  / manager or the organization and and his subordinate managers that handle employees and customers.  Here’s a brief story showing how this works.

An illustration:

Our entrepreneur  Joe starts out  with a vision to sell widgets to the world (or at least his home town).  He begins selling and becomes so successful that he must hire employees to help.  At this point Joe has to step back from dealing with customers directly and begin dealing with his employees if he wants to be successful.  Joe must devote some of his time to managing his people.  If he is successful at instilling his vision, methods, and purpose into the people he has hired then his business will continue to grow.

Now lets say that Joe is very successful and must hire or contract 30 people to handle the day in day out operations of his business.  Obviously Joe cannot deal directly with customers like he used to and probably spends most of his time coaching, training, and counseling his people on to success.  He has created a small pyramid structure where each employee or contractor reports to him.  Joe’s business expands and he opens a branch in another town.  He can’t be in both places at the same time so he has to hire another person to help manage.  The new person starts out with several employees and Joe’s plan, vision, and methods for selling widgets.

Joe now has two pyramids to handle,  the one he is directly involved in and the remote location.  This is the small business model.  As Joe continues down the road to success he continually adds more pyramids to his organization eventually creating units that handle marketing, legal issues, human resources, procurement, and financials.  By now Joe’s reached the point where there is no way he can run his original unit and properly motivate, inspire, and lead all the others so he hires another manager to handle his unit and spend all of his time now overseeing all the units.

Sounds complicated?  Well it really isn’t if Joe’s done some smart hiring but Joe does have quite an infrastructure of of people in place and a weekly obligation to do a set amount of sales in order to pay them all.  Joe’s done a great job of scaling up his business but the way he’s done it doesn’t leave him any room for scaling down.  Also, Joe is out of touch with his consumers now because he doesn’t get to deal with them directly so he can’t read market demands like he used to so he has to rely on the people he’s hired or contracted to get this information for him.  Joe’s business model probably looks like the picture below.

The traditional pyramid organizational structure
Joe's business organizational chart

As you can see Joe’s continuing success is placing him further and further way from his customers while his ability to make decisions that affect the outcome of the business has grown in proportion to its scale.  Joe’s answer to this problem would typically be to saturate his decision making process with inputs from the managers he’s hired and empower them to make some of these decisions.  He might occasionally drop in on departments or operations to see what is going on and attempt to get a better perspective of the needs of the business by talking directly to employees that deal with suppliers and customers, but for the most part he’ll be plugged into the network he’s built and be removed from the front lines of the business.  These are the effects of the traditional pyramid structure of business.

Strong points

  • Inherently allows for growth in the scaling of business.
  • Allows for intuitive growth of business
  • Authority and areas of responsibility clearly defined.
  • Clearly defined path for promotions and reward within the organization.
  • Internal units can create group cohesiveness, camaraderie and loyalties.
Weaknesses
  • Leadership is removed from front-line supplier, customer, and prospect interaction and may lack responsiveness.
  • Leadership must rely on subordinate sub leaders to supply information and analysis.
  • Top level decision making can be skewed by group thinking, the overriding desire for consensus, and group politics which do not reflect the businesses actual needs.
  • Front-line employee’s may have limited decision making ability and lack the ability to properly engage the customer or prospect.
  • Innovation may be stifled by top down communication.

In our next article we’ll discuss an alternative structure that could be used to improve responsiveness and innovation through networking.

Joel

 

TCPDF php package for pdf writing

I recently had opportunity to implement the TCPDF package for a midsized project. This article attempts to document my experiences with the API, its strengths, weaknesses, and ease of use.

The package is quite simple to implement at a high level, and following the included examples I was able to create a writer for my project in a matter of days. I appreciated the flexibility of being able to use HTML for layout. Also appreciated was the ability to override the TCPDF class to create custom headers and footers. I utilized this to place a reference to the company logo in the website’s image directory rather than in the tcpdf package’s image directory. I also was able to create a more detailed header layout than the default using this method. Once the pdf document is constructed, TCPDF provides some helpful output options including posting the document directly to the browser. This is a nice option because it allows previewing in an iframe, and doesn’t take up space on the server.

Initially I constructed a string containing inline style and the data in one large HTML table, and wrote the pdf document using one writeHTML call. An example of this follows:


$style="<style type=\"text/css\">\n";
$style=" table {\n";
$style=" color:red;";
$style=" }\n";
$style=" td {\n";
$style=" border:none;";
$style=" }\n";
$style="</style>\n";
$table="<table>\n";
$table=" <tr>\n";
$table=" <td>example</td>\n";
$table=" </tr>\n";
$table="</table>\n";
$html=$style.$table;
$tcpdfObj=new TCPDF('L','pt',true,'letter',false);
$tcpdfObj->SetHeaderData("logo.png", 100, 'pdf title', 'header text');
$tcpdfObj->setMargin(72,72,72,true);
$tcpdfObj->setHeaderMargin(72);
$tcpdfObj->setAutoPageBreak(TRUE,72);
$tcpdfObj->SetFillColor(0,0,0);
$tcpdfObj->setCellPaddings(0,0,0,0);
$tcpdfObj->setFont('sans','',10,'',true);
$tcpdfObj->AddPage();
$tcpdfObj->writeHTML($html,true,true,false,false,'');
$tcpdfObj->Output("test.pdf",'I');

This first implementation worked for a small test database, but failed when I tested it for larger ones producing out of memory errors. Raising php’s mem_limit didn’t solve the problem. I was able to work around this by dividing the writeHTML call into several smaller calls each with a copy of the inline style and a HTML table containing several rows of the original HTML table, but this added to the running time. writeHTML seemed to work with about 2500 cells at a time. Having overcome the memory limitation, I found that running time for large datasets was unnacceptable. It was in the range of 10 minutes or more for a 50000 cell document. Fortunately tcpdf has faster Cell, and MultiCell functions, however when using them layout becomes much more restrictive. Using these faster calls reduced the running time by 50%, but this was still too slow for my project.

To summarize, the tcpdf package works, offers some flexibility of layout and output, is quickly implemented, but doesn’t scale well.

PHP quick data export to spreadsheet

In our last post we talked about the limitations of creating large spreadsheets with PHP library PHPExcel.  Today we’ll discuss a quick workaround that will allow you to create large unformatted spreadsheets for quick and easy data export from your applications.  Here’s how we do a php quick data export to spreadsheet:

  • Properly escape your data.
  • Write data with fcsvput($filehandle, $yourdataarray, “t”);
  • Include table headings and other data.
  • Use a xls file extension.
Properly escape your data... You’ll be using a tab delimited format for output so you’ll need to replace the tabs with an escaped tab or five spaces so that your data doesn’t corrupt your output format.  For our purposes we’ll be using five spaces in the following function.
function TSV_Escape($str)
{
    if (!strlen($str) == 0)
    {
        $str=str_replace('t','     ',$str);
        if (!strstr($str,"n") === false)
        {
            $str=str_replace('n','%n',$str);
        }
        return str_replace('"','""', $str);
    }
    return '';
}

Write you data with fputcsv:  First you’ll need to open a file handle like this…

// Set file path and initialize handle.
$TSVFile = $_SERVER['DOCUMENT_ROOT'] . "/MyDataFile.xls";
$TSVFileHandle = fopen($TSVFile, 'w');
// Write your headers.. See next section :)
// Write your data.
// Write query data to csv.
if ($objdbconn->real_query($sql))
{
    if ($result = $objdbconn->store_result())
    {
        echo date('H:i:s') . "Processing " . $result->num_rows . " records.<br>\n";
        while ($row = $result->fetch_assoc())
        {
            $writeArr = array();
            foreach($row as $value)
            {
                $writeArr[] = TSV_Escape($value);
            }
            fputcsv($TSVFileHandle, $writeArr, "\t");
            unset($writeArr);
        }
    }
}
// Close your file handle.
fclose($TSVFileHandle);

Write your headers and other data:  You may want to include some information about your spreadsheet and you’ll certainly want to include the column header row.  Here’s a brief example of how this could be done:

$headings = str_replace('`', '', "Heading One,`Database Field 1`,`Database Field 2`,`Database Field 3`");
$headArr = explode(',', $headings);

$RepDat[]="Created: " . date('H:i:s d-m-Y');
$RepDat[]="Created by: " . $UserName;
// Write county name to csv file.
fputcsv($TSVFileHandle,$RepDat,"\t");
fputcsv($TSVFileHandle,$headArr,"\t");

Use a xls file extension.  Sure you could use a tsv file extension, but if you want Excel or Open Office to open the file by default with minimal headache the xls extension will do the trick.  You’ll get an message when you open the report stating that the file was not in the same format as the extension, but you won’t have to worry about the tsv file extension being registered to the right application.

This method will kick out a tab delimited spreadsheet in a matter of seconds and can safely handle large record sets.  We used it for a while, as a temporary fix for reporting, until we came up with a better method and we still use this method to create database load files when parsing complex legacy reports or backing up database records to file.

I hope this php quick data export method is helpful.

Joel

Excel spreadsheets with PHP – a PHPExcel overview

Writing Excel spreadsheets with PHP using PHPExcel:  The pros and cons

PHPExcel is a php library for reading and writing excel spreadsheets.  It is very well documented and has good community support.  When searching the web for an open source solution for writing spreadsheets in PHP I reviewed everything from PHPClasses to Pear and finally I came across this package.  It’s the most up to date looking project out there for excel spreadsheets with PHP.  I didn’t want to use a project that was in the twilight of its development cycle so I opted to try PHPExcel.  Here’s a a brief overview of what I found:

Pros – The good points:

  • Very well documented.
  • Good examples
  • Support forum with active participation.
  • Supports many of the builtin excel functions.
  • Easy to style
  • Supports modern Excel formats plus csv, html, and pdf
  • Write spreadsheets
  • Read spreadsheets
Cons – what I couldn’t stand:
  • SLOW….  This library takes considerable time to produce a spreadsheet when memory conserving disk caching is used.  Consider running your process in the background.
  • Memory Intensive  PHPExcel offers disk caching to reduce its in memory size, but it basically is an in memory spreadsheet and must load completely into memory while being before being written to file.  This can considerably hinder your performance as the spreadsheet object and writer object can take over 25 mg of ram while the program is running with an additional 1 kb of ram per cell loaded in memory.  For an example of how this can impact your server or hosting service consider the load of a 50 column 10000 row spreadsheet which would take 525 mb of ram to load when writing to file.  While its possible to set the scripts memory high enough to handle this you’ll find that if several of these scripts try to run at the same time you’ll have a mess that could crash your server.
  • Write to file is batched processed at the end of the script and happens all at one time.  Regardless of your disk caching settings the entire spreadsheet is loaded into memory and then written to the file.  This creates a serious bottleneck if you have a large file and will oftentimes crash your script.  The only exception to this is when PHPExcel writes a csv file in which it allows for a more granular approach to memory to file writing.
Workarounds that will reduce memory usage and improve speed.
  • Set a cells value explicitly.  Setting the cells value and data type explicitly is much faster than writing cell values for PHPExcel to determine the data type of.
  • Disable formula precalculation by setting it to false.
  • Use disk caching.
  • Don’t try to use it to create reports from large data sets.
In summary:  If you are trying to read and write to small spreadsheets with less than two hundred and fifty thousand fields or cells then this library will be a good fit for your project.  It’s great for summary reporting!!  However if you’ve got extremely large record sets that you need to send to a spreadsheet you’ll need a different approach.  I’ll be writing about how we did that in the next blog post.
Stay tuned and may the source be with you!!
– Joel

July 2011 in Retrospect

July 2011 in Retrospect:  Too busy to write but things are looking promising.

July 2011 in retrospect has been a tough on my blogging efforts.  My latest project has taken up so much time that between it, my day job, and my family, it’s been hard to get time to write.  This post makes number four during this month which is a considerable decline from what I’ve accomplished in the past so I guess I’m not to happy about the blogging results this month.  I never thought I’d be writing in a manner that anyone in the world could see my thoughts but I’ve found the process rewarding and I don’t intend on letting it go.  Some of the difficulty finding writing material stems from the confidential manner of the projects I undertake.  I tend to focus like a laser beam on what I’m trying to accomplish and when I’m putting a lot of effort into developing functionality for an entity that has exposed their core competencies to me the it tends to create a pool of experiences that I’m not comfortable talking about.  I value the trust that other have placed in me so I can’t write about things that they’ve placed in my confidence on the web for anyone to see.

That being said…  I’ve recently had the pleasure of hooking up with some of the brightest and hardest working people I’ve ever enjoyed working with in my life.  They’ve given me a chance to make a difference in in what they do by utilizing my technology and business skills to improve the efficiency of their process by leveraging technology to automating tasks and procedures and streamlining data flow.  I’m enjoying a synergy of the management, business, and technology skills I have in fuller manner then ever before and I appreciate the opportunity to analyse, innovate, and create that they have offered me.  Putting the icing on the cake,  I’ve been able to pull my brother Jeremy from valleyflight.com in on the project and I always enjoy working with him.  He has a depth of technical expertise, is always helpful, and listens to my ideas without telling me that I’m crazy for thinking too big.

Hopefully August will be a better blogging month.  I’ve got a packed schedule and I know that time will be an issue, but having experienced the power of blogging and how it helps shape thoughts and expression, no matter how busy I get I won’t be quitting the blog.  Sometimes I kind of think of this thing as a big public diary… I write about the things that fascinate me and some of the things that I’m doing and I’ll get the chance to go back someday and it will all be here.  I’ll be able to look back at this along with those that I know and love and see the path I’ve taken along with the milestones of yesterday.

July 2011 in retrospect: Here’s to casting a message in a bottle into the sea of information in hopes that someday it will was up on a future shore and I’ll see it and remember where I was when everything changed.

Be blessed,

Joel

 

What modern business applications should offer users.

Modern business applications should offer users the following features…

While developing solutions for various projects that I’ve undertaken I’ve come up with a few ideas on the types of features that I’d like my applications to offer users.  While this list is far from complete I think it would be good to post it for comment.  Bear in mind that when I’m discussing modern business applications I’m discussing thin client web based applications using cloud architecture.

Modern business application features:

  • Remote connectivity to data and functionality.
  • Encapsulation of business logic.
  • Continuous contextual decision support.
  • User specific views of the data and logical processes
  • Security
  • Flexibility
  • Data Importing / Exporting capabilities

Remote connectivity to data and functionality: Traditional business applications ran on workstations and desktop computers.  Data was stored on the computer itself or on a server and was not accessible unless the user was sitting in front of the desktop computer itself or another computer connected to the server.  This in effect chained the user to his or her desktop device.  Modern business applications must utilize web technology and provide device independent services that allow the user to connect to the data and logic of the business through any device that they can be authenticated through that has internet connectivity.

Encapsulation of business logic: Traditional business applications such as spreadsheets, word-processors, and email allowed for the transportation and transformation of data, but the use of business logic was largely left to the discretion of the user.  Modern business applications can be designed to encapsulate the steps that must be taken with information and resources to automate processes and insure execution of critical procedures required by users.  By profiling the procedures and steps required for critical processes in the business, developers can create software that encapsulates them and insures that the order of operations is followed, all steps required are taken, all resources required are employed, and follow through is complete.  Outcomes and ownership of inputs from each step can also be tracked to determine each users contribution to the success of the process.  Success ratios for processes can be increased as the mundane oversight of each detail is moved from managers to system applications with the general oversight of larger categories of processes taken on by tech empowered managers.

Continuous contextual decision support: Because of the connectivity offered by todays diverse array of computing devices, from smart phones, laptops, tablet PCs, to thin client enabled desktop PCs.  Users now have the ability to receive data and logic at any point of the business process.  Modern business applications must provide contextual decision support by offering relevant information to the user at the right time with suggestions for its proper use and allow for user feedback into the system.

User specific views of the data and logical processes: Modern business applications must offer users unique views of the data and logical processes that fits their context to the business.  For example a vendor that supplies a business would need access to statistics indicating demand for the particular commodity they offer.  Their view of the data and logic would be an on demand view or automated communication with forecasted consumption data generated by internal business processes that the vendor never sees.  User specific views of the data and logic offer modular controls to the business and protects its core competencies from probing by competition.

Security: Traditional business applications were prone to interruption by natural disasters and other disruptive events such as fires, floods, tornadoes etc.  Modern business applications can offer security to its users by storing data and logic in a cloud environment where information is distributed off site amongst computers in multiple data centers.  This offers a degree of security to the user and provides for a significant reduction in recovery time when the business is impacted by such an event.

Flexibility: Modern business applications created with web based technologies are more flexible than traditional business applications because of the ease in which updates can be rolled out to the user.  In traditional environments users had to undergo an application update procedure before receiving an updated version of a business application that contained the latest data and logic.  Web applications are updated remotely with no effort required by the end user making their innovation, iteration, and revision much more seamless and transparent to end users.

Data Importing / Exporting capabilities: Modern business applications should easily convert data with traditional applications such as spreadsheets and allow the user the comfort of converting data for use outside of the application.  Data transfer methods such as XML are a good standard for data export and can allow for data interchange between disparaging systems and applications.

Comments and discussion are welcome.

A quick php data sanitation guide

PHP data sanitation is the method of testing inputs and output for acceptable ranges of data to insure that a script will produce the desired result.  Data sanitation is sometimes referred to as a sanity check as insane things tend to happen when a script gets values it was never intended to process or renders values to the users browser that breaks the html document or javascript functionality of the page or worse yet cause the page to work in a manner it was never intended to.  PHP data sanitation for data input into scripts when the user is passing values in can be easily accomplished  in three steps and data sanitation for output to the users is even simpler.

Three steps for a php scripts data sanitation on input:

Step 1: Check for the existence of the required inputs from the four types of inputs you can use $_REQUEST[‘var_name’], $_POST[‘var_name’], $_GET[‘var_name’], and $_COOKIE[‘var_name’]. Use the function isset() to determine if the variable is set and doesn’t have a null value.  Use the function isempty() if you’d like to check to do the same type of test while accepting null values.  Tip don’t use $_REQUEST as you cannot validate where the data came from.

Step 2: Check inputs for approved data types. If the type doesn’t match reject the input value as tainted.  Functions for checking data types are as follows:

is_object
is_infinite
is_real
is_int
is_string
is_long
is_scalar
is_nan
is_double
is_uploaded_file
is_array
is_bool 

Step 3: Whitelist the input values by checking them for acceptable values and reject inputs that do not meet your specified input parameters.  Check for acceptable values using character type functions for strings and comparison operators for numeric values.   Ctype functions include:

  • ctype_alnum — Check for alphanumeric character(s)
  • ctype_alpha — Check for alphabetic character(s)
  • ctype_cntrl — Check for control character(s)
  • ctype_digit — Check for numeric character(s)
  • ctype_graph — Check for any printable character(s) except space
  • ctype_lower — Check for lowercase character(s)
  • ctype_print — Check for printable character(s)
  • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
  • ctype_space — Check for whitespace character(s)
  • ctype_upper — Check for uppercase character(s)
  • ctype_xdigit — Check for character(s) representing a hexadecimal digit

Comparison operator include:

Example Name Result
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b after type juggling.
$a <> $b Not equal TRUE if $a is not equal to $b after type juggling.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Pulling it all together with some pseudo code:  Encapsulate in function: IF isset(YourPostVar) AND isdigit(YourPostVar) AND YourPostVar >= 0 THEN return YourPostVar Else return false;  As you can see we combined all the stages here to insure that the numeric value we received was set, and was a digit with a value of zero or greater.

Note: When inputing data into databases use the dbms’s escape string functionality to insure that variables are properly escaped.  If the dbms doesn’t have an available escape string you can use addslashes().

Output sanitation is very simple. Always encapsulate output to the user with htmlentites() or htmlspecialchars() when sending data straight from inputs or a database.

Hope this helps.

Joel Caton

The importance of You(ser): You are important – I am important

The importance of You(ser): You are important.

Business got you locked up? :(  Break out with catontech tools!  :)

You are the center of your environment, your team, your family, and your business.  You’ve poured your life’s energy, your dreams, and all of your passion into your business and career and you deserve the best.

As the most important person in your life you deserve business solutions that work for you by:

  • offering you timely information about the important events surrounding and affecting your business.
  • providing easy access to measurements and metrics that indicate the performance or your organization.
  • automating time consuming processes and gives you the freedom to do the important things you do best.
  • freeing you from your desk and allow you to make decisions from anywhere in the world.
  • offering the power to transform and employ the information in your organization without effort or hassle.
  • securing the practices, procedures, and data of your core business against nature, accidents, competitive organizations, and criminals.

Your time is like money in your wallet and you deserve solutions that free you to spend your life pursuing your passions.  You started your business with a dream and you should be free to pursue it without sacrificing the things that are important.

You know the importance of your decisions in your organization and all that you’ve done to create the things around you.  Take a deep breath and think about the things in your environment that are keeping you from meeting your objectives.  Now breathe out and say I am important! I am too important to be tied up with things that keep me from my passions and dreams.  I’m too important to allow my business to tie me up in red tape and processes that keep me from focusing on the things I know are important to my success.  I’m too important to leave my success to chance.  Take a moment and write down the things that are keeping you from meeting your objectives and tying up your time.  Once you’ve reflected on them visit us at http://catontech.com/card.  We’d like to help you.  The conversation won’t cost you anything.  Just fill out the form first so we can focus on the issues and we’ll email you and set up a time to talk.

Click for an hour of consultation - no obligations - just listening and advice.
Joel Caton