PHP

12 Regular Expressions To Improve Your PHP Development

September 6th, 2010 0 Comments

In programming, regular expressions are a very useful tool designed to validate, search, and match text patterns. In this article, I have compiled more than 10 incredibly useful regular expressions, for any language, that will probably be very beneficial to you.

Validate an URL
Is a particular url valid? The following regexp will let you know.

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/
Source: http://snipplr.com/view/19502/validate-a-url/

Validate US phone number
This regexp will verify that a US phone number is valid.

/^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/
Source: http://snippets.dzone.com/posts/show/597

Test if a password is strong
Weak passwords are one of the quickest ways to get hacked. The following regexp will make sure that:

Passwords will contain at least (1) upper case letter
Passwords will contain at least (1) lower case letter
Passwords will contain at least (1) number or special character
Passwords will contain at least (8) characters in length
Password maximum length should not be arbitrarily limited

Get code within
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
Source: http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=297

Get code within
If for some reason you need to grab all the code contained within the tags, this regexp will do the job:

<\?[php]*([^\?>]*)\?>
Source: http://snipplr.com/view/12845/get-all-the-php-code-between/

Match tel: urls
In a recent post, I showed you how you can use iPhone special link prfixes to automatically call someone.
This regular expression will match those tel: urls.

^tel:((?:\+[\d().-]*\d[\d().-]*|[0-9A-F*#().-]*[0-9A-F*#][0-9A-F*#().-]*(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*’().-]|%[\dA-F]{2})+)?)*;phone-context=(?:\+[\d().-]*\d[\d().-]*|(?:[a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*(?:[a-z]|[a-z][a-z0-9-]*[a-z0-9])))(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*’().-]|%[\dA-F]{2})+)?)*(?:,(?:\+[\d().-]*\d[\d().-]*|[0-9A-F*#().-]*[0-9A-F*#][0-9A-F*#().-]*(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*’().-]|%[\dA-F]{2})+)?)*;phone-context=\+[\d().-]*\d[\d().-]*)(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*’().-]|%[\dA-F]{2})+)?)*)*)$
Source: http://tools.ietf.org/html/rfc3966#section-3

Validate US zip code
When building a registration form, it is common to ask the user’s zip code. As forms are often boring, there’s a strong chance that the user will try to register false data. This regular expression will make sure he entered a valid American zip code.

^[0-9]{5}(-[0-9]{4})?$
Source: http://reusablecode.blogspot.com/2008/08/isvalidzipcode.html

Validate Canadian postal code
This regexp is very similar to the previous one, but it will match Canadian postal codes instead.

^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
Source: http://reusablecode.blogspot.com/2008/08/isvalidpostalcode.html

Grab unclosed img tags
As you probably know, the xhtml standard requires all tags to be properly closed. This regular expression will search for unclosed img tags. It could be easily modified to grab any other unclosed html tags.

]+)(\s*[^\/])>
Source: http://snipplr.com/view/6632/grab-any-unclosed-xhtml-img-tags/

Find all CSS attributes
This regexp will find CSS attributes, such as background:red; or padding-left:25px;.

\s(?[a-zA-Z-]+)\s[:]{1}\s*(?[a-zA-Z0-9\s.#]+)[;]{1}
Source: http://snipplr.com/view/17903/find-css-attributes/

Validate an IBAN
I have recently worked on a banking application and this one was definitely a life-saver. It will verify that the given IBAN is valid.

[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}
Source: http://snipplr.com/view/15322/iban-regex-all-ibans/

Validate a BIC code
Another one very useful for any banking application or website: This regexp will validate a BIC code.

([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)
Source: http://snipplr.com/view/15320/bic-bank-identifier-code-regex/

If you’re interested in regular expressions, make sure you have read our “15 PHP regular expression for developers” post.

Adobe Dreamweavers Future For Developers

August 1st, 2010 0 Comments

OK, Dreamweaver has reused the recordset code for too long, but let’s look at the big picture for Dreamweaver CS5. The easiest front end development tool that exists… period. No one can take that away. In CS5, Adobe has finally stepped up their development game a notch.

As a PHP developer, it’s the changes in Code view that really excite me. When you start typing a PHP script in Dreamweaver CS5, you’ll immediately notice a red marker in the line numbers column and an alert about a syntax error. Complete the line without errors, and the marker and warning disappear. Dreamweaver constantly checks your syntax on the fly. It doesn’t tell you what the errors are, but it highlights all lines with errors, making the debugging process much quicker. PHP code hints have also been improved dramatically. There’s full support for all core functions, constants, and classes (as of PHP 5.2).

Code hinting is also much smarter. Instead of needing to search through code hints alphabetically, Dreamweaver CS5 searches for substrings. This is helpful when you can’t remember the exact name of function or class—just type the part of the name that you remember, and Dreamweaver includes it in the list. You can also work out your own shortcuts. For example, if you press Ctrl+spacebar and type gesi, the code hints take you straight to getimagesize() by recognizing the ge of “image” and the si of “size”. And in case you don’t know how a function or class works, the official manual page—complete with code examples—appears as a tooltip at the bottom of the selected code hint.

For serious PHP developers, it gets even better. Dreamweaver CS5 is capable of code introspection, so it builds code hints on the fly for your own functions and classes, as well as for third-party libraries, such as the Zend Framework. The definition files don’t even need to be directly attached to the page you’re working in. With Site-Specific Code Hints, you tell Dreamweaver where your library files are located, and it scans them for you automatically.

So should you upgrade? Seriously, you’re asking that? YES… it’s the best version of Dreamweaver that’s existed.

Never Use $_GET Again… SAY WHAT?

August 1st, 2010 0 Comments

You don’t need to use $_GET or$_POST anymore. In fact, you probably shouldn’t use $_GET and$_POST anymore. Since PHP 5.2, there is a new and better way to safely retrieve user-submitted data.

How many times have we heard about security issues in PHP applications stemming from unescaped GET and POST parameters? Proper escaping of input is a perennial problem with web development in general, and for whatever reason PHP seems to have had more than its fair share of bad publicity on this front.

On the database side, many worries over SQL injection have been squelched. The clever developers of PDO, for example, have constructed a library that analyzes data and escapes it appropriately. But the problem of validating and sanitizing input is still a substantial issue. To my surprise, many seasoned PHP developers still spend precious development cycles building custom code to filter input.

Why is this surprising? Because PHP (from 5.2 onward) has a built-in filtering system that makes the tasks of validating and sanitizing data trivially easy. Rather than accessing the$_GET and $_POST superglobals directly, you can make use of PHP functions likefilter_input() and filter_input_array(). Let’s take a quick look at an example:

<?php
$my_string = filter_input(INPUT_GET, ‘my_string’, FILTER_SANITIZE_STRING);
?>

The code above is roughly the equivalent of retrieving $_GET[‘my_string’] and then running it through some sort of filter that strips HTML and other undesirable characters. This represents data sanitization, one of the two things that the filtering system can do. These are the two tasks of the filtering system:

  • Validation: Making sure the supplied data complies with specific expectations. In this mode, the filtering system will indicate (as a boolean) whether or not the data matches some criterion.
  • Sanitizing: Removing unwanted data from the input and performing any necessary type coercion. In this mode the filtering system returns the sanitized data.

By default, the filter system provides a menagerie of filters ranging from validation and sanitization of basic types (booleans, integers, floats, etc.) to more advanced filters which allow regular expressions or even custom callbacks.

The utility of this library should be obvious. Gone are the days of rolling our own input checking tools. We can use a standard (and better performing) built-in system.

Filters won’t solve every security-related problem, but they are a tremendous step in the right direction when it comes to writing safe (and performant) code. It’s also simpler. Sure, the function call is longer, but it relieves developers of the need to write their own filtering systems. These are darn good reasons to never use $_GET (or $_POST and the others) again.

How Do You Decide Between C#, Java, PHP, and Python

July 26th, 2010 0 Comments

In particular, a debate between the C#/.NET/IIS stack and the Java/J2EE/Apache/Solaris stack and the PHP/Apache/Linux stack could go on and on for years and years and you’d never find the right answer. That’s because there are so many pros and cons of all these platforms that advocates of each side can debate and debate and never get any closer to the truth, but it sure as heck is a fun debate.

There’s so much evidence that when it comes right down to it, millions of people are building huge business-critical things in C#, Java, PHP, or Python, and while they may have problems, they’re not mission threatening problems.

So how do you decide between C#, Java, PHP, and Python? The only real difference is which one YOU know better. If you have a serious PHP guru on your team who has built several large systems successfully with PHP, you’re going to be a heck of a lot more successful with PHP, not because PHP is a better language than C#, Java, or Python, but because he knows it better

PHP 5.2 Is Dead

July 25th, 2010 0 Comments

OK, all you slow to convert technology anchors, let’s get with the program.  Reading between the lines, clearly the people developing PHP are tired of supporting the past.  And I agree.  There is no good that can come from forcing this language development to support legacy and sometimes just bad ideas unless you want to see MSs C# take over the world.  And the PHP frameworks out there still trying to put a smile on faces of 4.x users should take the hint as well.

PHP announced with its most recent sub set release of 5.2.14: This release marks the end of the active support for PHP 5.2. Following this release the PHP 5.2 series will receive no further active bug maintenance. Security fixes for PHP 5.2 might be published on a case by cases basis. All users of PHP 5.2 are encouraged to upgrade to PHP 5.3.

Use the latest or jump over to the sinking ship known as RoR… peace out.

Top 10 Reasons Why CodeIgniter Rocks

July 13th, 2010 0 Comments

CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you’re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you’re tired of ponderously large and thoroughly undocumented frameworks, CI might be for you.

10. MVC Architecture
The model, view, controller architecture is nothing new. It seems like all the coding frameworks are MVC nowadays, and if they aren’t it can be configured easily. I have had experience building large apps the procedural way and every time they end up with unmanageable spaghetti code. The MVC way of doing things offers nice code separation and keeps things clean. Some frameworks force you to do things by the books but CI lets you use MVC in a way that makes sense you. If that means ignoring models all together then so be it.

9. Little to no server requirements.
Unlike other PHP frameworks, CI works with both PHP 4 and 5. That makes the lives of someone like me who has to be able to work seamlessly between the two environments much easier. Of course I have painted myself into a corner from time and used PHP5 techniques in my apps, but the framework itself works on either.

8. Easy to understand and extend.
CI is the first framework that I used that actually makes sense to me. I have tried Cake PHP, the Zend framework, Symfony and many others and I was able to get up and running with CI the quickest. CI is also easy to write new libraries, change the behaviour of existing libraries and just change the overall behaviour of the framework with little effort.

7. All the tools you need in one little package.
Calendar, e-mail, zip encoding, validation, uploading, sessions, unit testing… that is just a few of the built in libraries that come with CI. It also includes a boat load of default helpers for things like forms, file handling, arrays, strings, cookies, directories and more. Plus, if that wasn’t enough, you can create your own libraries and helpers or use code that has been developed by the CI community and posted to the wiki.

6. No “installation” necessary.
Believe it or not, one of the hardest things I have experienced with trying new frameworks is installing them. I am not a fan of UNIX command line so I tend to look for tools that I can install and use by just uploading files to a directory. CI fits this requirement nicely. No need for PEAR packages or server modifications to get the framework up and running. Just upload the files to your server and your off.

5. Built in security tools.
CI allows you to implement as much or as little security as you feel is necessary for your app. It does some things by default like unsetting all global variables regardless of PHPs register_globals directive and turning off the magic_quotes_runtime directive during system initialization so that you don’t have to remove slashes when retrieving data from your database. Other things can be enabled like cookie encryption, handling session data with a database and automatically escaping SQL queries.

4. Database abstraction and more.
Every decent framework has a database abstraction layer nowadays and CI is no exception. You can easily create insert, update and delete statements without needing to write raw SQL. Handle connections to multiple databases within one application and connect to any of the following database types: MySQL (4.1+), MySQLi, MS SQL, Postgre, Oracle, SQLite, or ODBC. CI also lets you manipulate your database like add/remove columns from tables, create new tables and remove old ones using it’s new database forge library.

3. Large and active user community.
The last time I checked, there were over 57,000 registered members on the CI forums. That is a nice and big user community to work with when you have a problem or question. The CI website has a forum and wiki when your looking for answers. No confusing group mailing lists or chat channels just to get a quick answer to a question.

2. Excellent documentation.
By far, the biggest advantage of CI over any other framework is it’s documentation. I will admit to trying some other frameworks while they were still in BETA and under development. But, CIs documentation is 10 times better than other framework documentation I have come across and I strongly think thats because CI is backed by a company and not just a community. EllisLab, the company behind CI, takes a lot of pride in CI and they have big plans for it and thats why they don’t have a problem in spending the time that is necessary to come up with quality documentation for the user community.

1. One in the same with ExpressionEngine.
The #1 reason why CI rocks is that ExpressiongEngine, EllisLabs content management system, is currently being built on the framework. This means that whatever libraries, helpers, etc. that you develop for CI you can use with EE in the future and vice versa. This also means that whatever EE needs to operate, CI gets. This could means things like an improved parser class, built in user authentication, ability to easily program modular applications and more.

If you like to development using an OO framework… there’s no better place to start then CodeIgniter.