Sep 27

PHP LogoDid you know that PHP has some pretty powerful type casting functionality built-in? It’s no surprise if you comprehend the roots of PHP (since it’s written in C), but I can’t help but think that casting is an often-missed tool when a PHP developer is trying to ensure data integrity.

Just for a moment, let me define type casting in case you weren’t “in the know”:

According to Wikipedia, “in computer science, type conversion or typecasting refers to changing an entity of one data type into another.

So, in laymen terms, casting is an easy way to turn one type of data into another type. For example: converting a “string” variable filled with essentially text into an integer variable containing the same numbers but now representing a value. This makes it easy to do math with the value of what once was just a random string of characters.

The following cast types are allow in PHP:

  • String – (string)
  • Boolean – (bool), (boolean)
  • Integer – (int), (integer)
  • Binary – (binary) [PHP 6]
  • Floating Point – (float), (double), (real)
  • Array – (array)
  • Object – (object)

So, in the real world, when does casting actually come in handy?
Normally, PHP handles all this stuff automatically behind the scenes. But, as is normal, dealing with MySQL database interaction is something to always take seriously — and type casting can help you out!

We’re going to assume your aren’t using the PDO Prepare statement (though you should be). As a PHP developer, a major part of your job is containing the inherent security risks of user input. It’s especially important when these inputs interact directly with the database.

So, your simplified (e.g. – don’t complain) database interaction code might look something like this:


$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . $id;

Call me an overly nervous Ned, but I’d prefer to use the following code:


$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . (int)$id;

Did you notice the subtle change? See the ‘int’ cast of the $id in the SQL statement?

This should certainly help to ensure that I haven’t missed any security holes for this query. Some might say it’s overkill, but I just wanted a simple explanation for using casting, so get off your almighty soapbox already.

Anyways, as you can see, type casting in PHP has real-world uses. Delve into type casting a little more and you’ll find a huge number of cases where it can make your code that much more bullet-proof.

So seriously, try out PHP Type Casting.

Aug 01

Capistrano LogoIf you aren’t familiar with Ruby on Rails, there’s a good chance you’ve probably missed the proverbial boat on a powerful tool called Capistrano.

Do you ever feel like you’re repeating previous work every time you deploy a new application (or when modifying an old one)?  It’s a process I truly despise for two important reasons:

1) I really don’t like to feel like I’m being inefficient.
2) I hate wasting my own valuable time.

Ok, so 1 & 2 are sorta the same reasons… but you get my point.  A fellow programmer friend (a staunch RoR addict) recommended I try deploying my apps with Capistrano, even if they were PHP.  I had never really thought of that idea, but in reality, it made a whole lot of sense.

Anyways, originally I was going to write up a nice how-to on PHP deployments using Capistrano, but I decided the topic was already sufficiently covered.  It’s a good read and I’ll bet you’ll walk away excited about the amount of time you can save.

No more manual exports or checkouts from SVN again!

So, go check out this write-up at Simplistic Complexity for all the details.

Jul 15

The Future of PHPIf you are a fan of language “X” and think it’s better than PHP, here’s your chance to convince me. After some discussion with colleagues, I’m very interested to find a general consensus as to which web development language (server-side) is the true “future of web development”. My research reveals that PHP is the most popular web development language currently. Even though it’s clear that PHP is widely accepted, how long will that be true? Is PHP dying?

Now please don’t get me wrong, PHP is a great language that I use daily. It’s powerful, widely supported, popular, and pretty darn stable. Recently, I’ve even had even more success with PHP by supplementing it with CakePHP, a powerful PHP framework that makes development a bit more painless.

Still, even with frameworks and new versions of PHP coming soon, how long can the trend last?

Are you wondering why I care so much?

The reasons are fairly mundane: job security, stability, trends, and money.

I value my career and work as a web developer. We (web developers) provide content to the voracious users of the web and I love being a part of the “internet revolution”. I also enjoy keeping up on the latest trends… I tend to prefer being near the bleeding-edge at all times. Why? Because it’s more fun. Also, I’d say that having a grasp of where the future is headed in web development can be very valuable indeed.

Back to my point: I’ve played with a few alternate languages outside of PHP, but I’m not convinced of their long-term popularity… they just don’t offer anything revolutionary. Maybe I’m expecting a revolution that isn’t gonna happen. Or, maybe I missed the revolution boat already.

So, you tell me; what’s the next revolution? Has it even been invented yet?

Jun 23

Perl?Recently at work, a brief discussion with a co-worker about Perl vs. PHP encouraged me to do some “reading” about the topic.

Honestly, I had never really considered that people were still using Perl on a regular basis for web applications in the year 2007.  However, my research quickly proved contrary.  Truthfully, I haven’t touched Perl since I was a freshman in College nearly six years ago, so I suppose I’m a tad out of the loop.

This is what I can say though.  Perl is powerful, I’ve always known that.  See… I admit it, I respect Perl.

However, my life as a web developer is easier with PHP (and associated frameworks) than it would be with Perl, at least in my humble opinion.  In fact, if you consider my recent switch to CakePHP (a powerful & flexible PHP framework), I’d venture to say that I could never get the amount of rapid work, prototyping, and other efforts completed if I was forced to use Perl; no matter how many Perl modules I had access to.

I know it’s not fair of me to say that (since I’m no Perl expert), but still… if you are a die-hard Perl addict, you should take a moment to try PHP for your web applications; and take extra care to try CakePHP.  I’m betting you’ll be blown away by the time you save and the efficient code you generate.

Apr 27

KeysOne of the inherent flaws with any popular web language like PHP is the serious potential of security vulnerabilities from improperly set up installations and servers. Although ensuring a secure server installation (whether Apache or IIS) is extremely important, that process is outside the scope of this article.

Instead, I’d like to recommend one simple tool that will should enable you to pro actively plug most “holes” in your PHP setup.

The ironic part about this article is that just a short while ago I thought I had everything “plugged” myself. I had done my reading up on PHP security and felt confident that I had a secure setup. Unfortunately, in an upgrade to a more recent PHP version, I accidentally overwrote my “secure” php.ini from the previous install. This caused one particular web site to be infiltrated by a nefarious ‘hacker’. Fortunately, there was no serious damage and I quickly found the problem.

However, if I had dropped PhpSecInfo onto the server and checked it out before going live, I would’ve immediately known there was a problem.

So here’s how it works: PhpSecInfo is just a single script and a small library that does the work. You simply drop the PHP files onto your server and execute index.php in your browser. You’ll be treated with a nice looking, clean, and easy-to-understand table of security information about your current PHP setup.

There are a mighty large number of security tests performed and all you have to do is analyze the results. Using the highly familiar red, yellow, green color schemes (from stop lights)… you know which tests have failed miserably, which ones you should probably check on, and which ones you can safely ignore. I realize that it’s not the end-all security check-up for a PHP installation, but I think it’s truly helpful to anyone operating a public facing PHP web server.

So, if you’re interested, check out PhpSecInfo from the PHP Security Consortium.

Whether or not you make any changes to your setup, it’s always good to be aware of your vulnerabilities. Oh yeah, it’s also totally free!

Feb 23

cakephp.gifAfter literally weeks of tenuous back and forth rhetoric with myself (internally) and my fellow co-workers, I have finally, humbly, and assuredly concluded that CakePHP is the best PHP Web Framework in the world!

I could argue the benefits of Cake vs. other Frameworks again, but I’ve already done that, twice (though I originally decided differently).

Instead I’m hoping to help the Cake community a bit today. I’m not a “Cake expert” yet, but I think I can contribute a few things that can possibly ease some of the few frustrations that might occur when getting started with Cake.

Dustin’s CakePHP Beginner’s Guide!

I’m gonna try and keep it simple (K.I.S.S.) for ya’ll and do my best to actually offer any Cake newbies out there some advice that can help get the ball rolling quicker.

After showing it off to my co-workers and going through the manual a few times, here’s my

reccommended approach to the learning process:

First, Some Installation Tips:

- Use Apache… it’s just easier than IIS and it’s time to make the switch if you haven’t yet. Make sure mod_rewrite is enabled; again to make things easier.
- If you must use IIS, check out my writeup to help you get the ball rolling.
- “Make sure that an .htaccess override is allowed in your
httpd.conf (Apache), you should have a section that defines a section for
each Directory on your server. Make sure the
AllowOverride is set to All for the
correct Directory.”
- Don’t mess with the production install of Cake yet; just do a development setup.


Second, do the basic blog tutorial:

- Prepare for the inner excitement that will soon come.
- I know it’s not the recommended order of learning, but I think it works better to give a real-world example right off the bat before anything else.

Third, save that blog code and start working your way through the manual:

- Start at the very beginning, don’t skip any sections, and read every word.
- When you get confused (which you probably won’t much), re-read!
- It’s not a big manual, you’ll be done in an hour or two.


Fourth, go watch a few of the screencasts:

- Especially: Building The Bakery & Admin Routing

Last, start your own basic project and see where you get.

Here’s a few more helpful tips:

- Explore the Bakery for cool stuff.
- Get the ‘Cakesheet‘, it can save some serious searching time.
- Use the Cake Google Group, en excellent option for help.
- Remember to search through the User Manual, API, the web (2.1 million results for Cakephp on Google), and the entire Google Group BEFORE asking a question. You’d be surprised how often I see thread’s on the group posted that look something like: “Cake N3wbie – How do I connect to a database”. I know it’s easy to just ask and be lazy, but trust me, there’s a really good chance it’s already been answered. Don’t wear out the Cake experts prematurely with the simple stuff.

Ok, now you have enough to get started, so why are you still here reading this?

By the way: Let me know how Cake works out for you!

Feb 09

cakephp.gifLately, I’ve been taking some serious time out of my schedule to sit down and really examine a few of the top PHP Web frameworks (CakePHP, Symfony, & Zend) even more than I had previously. After a bunch of reading, tinkering, and playing around, I can now officially declare: “I think CakePHP is the best”. There I said it, I hope I won’t regret it… heh.

In fact, after actually sitting down and expanding on the basic blog tutorial offered in the manual, I am tepidly excited about the prospects of implementing something cool and truly useful in Cake (I may even switch The Weber Report over to my new, fancy, Cake-Powered, conglomeration that I created during the learning process) and really start taking advantage of the MVC Design Pattern.

Now that I have read through the manual a few times, I can humbly offer some of my favorite parts of the Cake experience:

Powerful Associations Between Models

“One of the most powerful features of CakePHP is the relational
mapping provided by the model. In CakePHP, the links between tables are
handled through associations. Associations are the glue between related
logical units.

There are four types of associations in CakePHP:

- hasOne
- hasMany
- belongsTo
- hasAndBelongsToMany

When associations between models have been defined, Cake will
automagically fetch models related to the model you are working with.
For example, if a Post model is related to an Author model using a
hasMany association, making a call to $this->Post->findAll() in a
controller will fetch Post records, as well as all the Author records
they are related to.”
Powerfully Flexible Data Validation Features

“Validations are defined using Perl-compatibile regular expressions,
some of which are pre-defined in /libs/validators.php. These are:

- VALID_NOT_EMPTY
- VALID_NUMBER
- VALID_EMAIL
- VALID_YEAR

But custom validation (outside of regular expressions) is also extremely easy. If you’d like to perform some custom validation apart from the
regex based Cake validation, you can use the invalidate() function of
your model to flag a field as erroneous. Imagine that you wanted to show
an error on a form when a user tries to create a username that already
exists in the system. Because you can’t just ask Cake to find that out
using regex, you’ll need to do your own validation, and flag the field
as invalid to invoke Cake’s normal form invalidation process.”


Stringent Security Component

“The Security component is used to secure your controller actions
against malicious or errant requests. It allows you to set up the
conditions under which an action can be requested, and optionally
specify how to deal with requests that don’t meet those requirements.

So if a request doesn’t meet the security requirements that we
define, what happens to it? By default, the request is black-holed,
which means that the client is sent a 404 header, and the application
immediately exits. However, the Security component has a
$blackHoleCallback property, which you can set to the name of a custom
callback function defined in your controller. Rather than simply give a 404 header and then nothing, this
property allows you to perform some additional checking on the request,
redirect the request to another location, or even log the IP address of
the offending client.

Every time the Security component is loaded, even if it is not
being used to protect an action, it does the following things: First, it
generates an authentication key using the core Security class. Then, it
writes this key to the session, along with an expiration date and some
additional information (the expiration date is determined by your configuration file).
Next, it sets the key in your controller, to be referenced later.

Then in your view files, any form tag you generate using
$html->formTag() will also contain a hidden input field with the
authentication key. That way, when the form is POSTed, the Security
component can compare that value to the value in the session on the
receiving end of the request. After that, the authentication key is
regenerated, and the session is updated for the next request.”

Cool Scaffolding (Similar to Rails)

“So cool that you’ll want to use it in production apps. Now, we
think its cool, too, but please realize that scaffolding is… well…
just scaffolding. It’s a bunch of stuff you throw up real quick during
the beginning of a project in order to get started. It isn’t meant to be
completely flexible. So, if you find yourself really wanting to
customize your logic and your views, its time to pull your scaffolding
down in order to write some code.

Scaffolding is a great way of getting the early parts of
developing a web application started. Early database schemas are
volatile and subject to change, which is perfectly normal in the early
part of the design process. This has a downside: a web developer hates
creating forms that never will see real use. To reduce the strain on the
developer, scaffolding has been included in Cake. Scaffolding analyzes
your database tables and creates standard lists with add, delete and
edit buttons, standard forms for editing and standard views for
inspecting a single item in the database.”

Remember, these are just some of the highlights. There is a LOT more in the manual to get you excited. In the near future, I’d really like to contribute a bit to the Bakery and really begin discovering the power of Cake in ways I can’t yet foresee.

You know you want to check Cake out, so stop wasting time… take the leap!

Jan 25

cakephp.gifOver the last few weeks, I have been attempting to learn two major PHP frameworks: Symfony & CakePHP.

Originally, I had decided (in a bit of short-sighted wisdom) that Symfony was the obvious champion. I think I may have been wrong. I spent nearly a week tinkering with Symfony off and on. I came to a simple conclusion: I’m confused.

The Symfony framework is so huge and poorly supported that it confused the heck out of me. Their basic “sandbox” tutorial doesn’t work in any way close to what the documentation states. And the documentation, oh the documentation; what could be the best part of this huge framework fails because of one fatal flaw: no one updates it for the new each new revision that (sarcastically) seems to come out every other day.

After seeing my co-worker struggle with the installation process for days and my own copy just barely functional (with hardly a thing to show from it), I called it quits. At least until I read this (from The Symfony Blog):

“You know that we spent the last months writing a complete guide for
symfony that will be released in bookshops on January 29th. We also
mentioned the fact that the content of this book would become the
official symfony online documentation and be published in HTML on the
same date.”

So, it looks like I’ll put Symfony off until this new-fangled documentation goes live, then I’ll give it another swing.

In the mean time, I’ve been working with CakePHP and genuinely lovin’ it. After tinkering around with it for a while, here are my thoughts about the two frameworks:

Documentation
- CakePHP: Up to date, but not totally complete and somewhat difficult to search through. They also have an extremely helpful CakePHP Google Group that helped most problems I ran into quickly (almost instantaneously during normal business hours) and efficiently. You can’t beat live support that’s free.
- Symfony: Until the new release, not all that helpful because much of the content is dated. However, what is there is easily searchable and they have an active forum that seems to be full of knowleable (yet somewhat arrogant) people.

Installation
- CakePHP: Very easy to install. For the most part, just copy it into your web root and you are good to go (provided you have Apache and mod re-write previously enabled). Once it’s in there, all you really have to do is setup the DB connection and you can be off and running.

- Symfony: Ouch… this is my major sticking point here. I know people that would say, “If it’s not hard, it’s not worth doing”. I agree with that idea, but this is one tough cookie to crack. There are so many little tricks, files, variables, and directory permissions to set-up… it’s a wonder I even got to the point I did. Their basic tutorial, “my first project“, wouldn’t work by following the given instructions… no matter what I did. They also rely on Pear to deliver the goods, which is inherently fraught with little tricks to keep it all running smoothly.

Directory Structure
- CakePHP: It makes sense and it’s extremely logical for almost anyone. You don’t have to be the creator of the framework to understand what each directory is used for. The framework code is in a separate directory totally away from all of your own code. Props to these guys, it works well.

- Symfony: File and directory overload. We’re talking a huge amalgamation of directories buried within directories and files scattered all over the place. When I started really digging, it left me dazed. Truthfully, after spending countless hours working with Symfony, I still haven’t figured out what all the directories are there for (which could be because the framework kinda mixes it’s own libraries in with the programmer’s code).

I could go on for hours, but I think you get the picture. For the time being, I have revised my opinion on the matter of PHP web frameworks. In my somewhat humble opinion, I think CakePHP is the current champion. However, Symfony may present some good competition just as soon as their new release comes out on the January 27th, 2007. Only time will tell I suppose. Rest assured, I’ll be choosing one or the other.

UPDATE: My mind is made up – CakePHP wins! Please read this, and this.

Jan 18

symfony-logo.gifThanks to a great mentor (Greg) in my starting days of web development and a strong background in Computer Science from several excellent professors in college, I had a good start at web development a few years back. My original skills for PHP featured an Object oriented approach, secure validation & error reporting, some nice Pear DB functionality (with MYSQL), and the Smarty Templating Engine. My skills and knowledge regarding PHP have continued to grow each day (especially regarding efficiency and security).

Recently though, I began playing with the big new talk of the town: Ruby on Rails. I have to admit, the process hasn’t been as easy as I thought. Most of the slowdown revolves around the fact that I don’t know Ruby all that well. Combining a totally new realm of development (the Rails framework) with a new language makes the switchover difficult for me. Regardless of the difficulties, I certainly see the power of Rails and understand how it’s framework can make the development process amazingly more agile and efficient.

With that being said, at Consumer Testing Labs we’ve been talking extensively of doing some major changes to how we code. We thought it would be a great idea to implement a standard templating system (like Smarty) for everyone to use, develop some internal libraries that all the developers could agree on and use frequently, and even strong rules on everything from coding practices to directory structures to design patterns. I think we all sorta hit a no duh moment when considering how to implement all these ideas effectively: a PHP MVC framework!

The discussions at work piqued my interests enough to send me on a quest of nightly rituals over the last week or two discovering, testing, and playing around with the nearly fifty frameworks that currently exist for PHP. Ok, I didn’t try them all out, but I did try out the best of the best according to my reading (and the ones that seemed to fit into the MVC layout). After tinkering around with CakePHP, Zend Framework, and Symfony, I did a lot more reading on these types of agile development packages.

Here are my conclusions on things at this point in time (01-17-2007):

CakePHP: Had a great basic install and easy to implement first run of things. I really liked being told what to do from the Cake code itself. Sorta like a wizard. Getting into more advanced coding had me pulling my hair out though. Mostly, the documentation was at fault – but not that it was all lacking. I just thought it was sorta scattered and hard to follow. Some tutorials I found helped a bit, but I was still left confused much of the time.

Zend Framework: Where do I begin? I had an icky feeling from the get-go with this thing. First, I’ve been a little off put by Zend for trying to commercialize something that has for so long been open-source… at least for the most part (PHP). In my opinion, the problem with the Zend Framework is that it appears to be a half-hearted attempt at a framework. It seems like it’s more like a collection of libraries than a true framework. When I compare it to Cake and Symfony or even Ruby on Rails, it just doesn’t feel quite right. There are lot’s of specific reasons I feel this way, but anyone’s attempt to convince me otherwise would simply be futile, heh. I don’t think Zend would ever be the type of framework I would want to use on a daily basis (at least until they make some major revisions or enhance it a bit more).

Symfony: If you hadn’t guessed it yet, Symfony was the winner in my book. I saw a lot of true similarities here between it and my reference: Ruby on Rails. Now, don’t get me wrong; it isn’t a straight-up clone of Rails, but the good parts are all there. So what does this mean to me? It means I get to use all the power of the Rails framework (albeit a tad different) without having to learn an entire new language (Ruby). It’s the best of both worlds!

So, if you are out there looking for a well-rounded and properly executed PHP web framework, be sure to check out Symfony.

UPDATE: I have actually changed my mind! Please read this, this, and this.

Nov 21

Just a quick hint for all you web developers out there in the world. 

The past week I have been struggling to implement a few draggable items and some accordion action on a project I've been working on at work. 

I found that Script.aculo.us is still a bit buggy in this department.  I stumbled across another similar effects/utility library that seems to work a lot better, is a bit lighter on file size, and seems to be a tad easier to implement (at least away from a Ruby on Rails platform). 

It's called Rico and it's quite nice.

Check it out if interested.

Nov 06

This week at work I've been struggling with a relatively simple problem that is disturbingly difficult to solve (at least as a humble web developer like myself).

Basically, I need to generate a dynamic, database-driven, menu system that will allow me to make some highly complex (tree-like) decisions based on user decisions.  Ok, stated out like that, it may seem to be a complex problem.. but it's not, I promise.

In more simple terms, I need a drop-down menu system that will allow a user to “drill-down” to the proper final output without having to click on twelve submit buttons and having a lot of constraints on what they can pick depending on what was chosen in the last drop-down.   I'm attempting to mix some Script.aculo.us, AJAX, and a Pear tree (a PHP plugin which was last updated on 3/17/03 as a beta). 

Let me give a real world example of what I'm trying to do.  You can imagine my problem by thinking about how you would implement a car repair web site.  If you wanted information about your 2002 Ford Mustang's automatic transmission: you would first pick “2002″, which would then fade in a new drop-down with all the valid 2002 car models… so then you pick “Ford”… which would then fade in another new drop-down with all of the valid 2002 Ford models… now you pick Mustang… we get a new drop-down with the different 2002 Ford Mustang models… I think you get the idea.

The real problem is in doing this efficiently, elegantly, and enhancing the experience with a touch of Scriptaculous.  It's tougher than you might guess.  I'll let you know how it ends up!

A special note to Jim: Yes, I know this problem might be easier solved in Rails, but who says a challenge isn't fun?