Apr 14, 2009 by Matt | Posted in Coding
PHP is an easy scripting language to learn, but mastering it is a whole other matter. Here are a few common mistakes that beginners, and even experienced PHP developers, might make once in awhile.
They’re not really visible mistakes, such as the ones that would result in an error message. They’re the sort of thing that might go unnoticed, but could really use fixing.
- Calling a function more than once unnecessarily. Suppose you need to, in two places, use the length of a string variable to do something. Don’t call
strlen($var) twice, call it once and save the result to a new variable (name it something like
$var_len). Then you can use the variable wherever you need the length. If something will have the same result, only do it once. You’ll save a few CPU cycles.
- SQL Injection vulnerabilities. SQL Injection is one of the more popular ways for those up to no good to attack a website. Any user-submitted data should be properly escaped before being worked into a database query. Otherwise a seemingly harmless search box or login form could be used as a gateway to your database, opening you up to data theft or deletion. Read up on SQL Injection and how to counter it.
- Not encrypting passwords. Please, never store users’ passwords in plain text. Any software that requires a user to log in with a username and password should use a one-way hash to turn passwords into meaningless gibberish. Users trust you with their login credentials, and they likely use the same ones across multiple sites (despite recommendation otherwise). Don’t let them be stolen. Password Hashing.
- Using 302 redirects instead of 301s. It’s fairly easy to redirect with PHP’s header function. However, it doesn’t do a 301 redirect automatically. It uses a 302 HTTP code, which can cause duplicate content issues with search engines. To do a 301 redirect, you must send a 301 response header before the location header. Sending a 301 “Moved Permanently” Header with PHP.
- Not using OOP. The object-oriented approach to programming takes a bit more planning that the procedural approach, but it’s worth learning if you haven’t already. It makes for much cleaner code. CSS-Tricks.com has a nice tutorial on how to build a basic object-oriented CMS. While not exactly a primer on PHP OOP, it’s a good hands-on experience. For a ground-up introduction to classes and objects, try Killer PHP’s Object Oriented PHP for Beginners.
Apr 2, 2009 by Matt | Posted in Coding
CodeIgniter is a PHP framework that incorporates the MVC methodology. It’s fairly lightweight, doesn’t require messing around with the console, and once you get used to it, it might make it easier and faster to code.
CodeIgniter simplifies many tasks, such as database I/O and form handling, it’s modular architecture allowing you to load various libraries when you need them. It uses the Model-View-Controller design pattern, where the “View” files are templates and such, with the Models and Controllers doing the heavy lifting. Overall the framework tries to promote cleaner, more efficient coding.
Some people don’t like frameworks, some people are lost without them. I’m somewhere in between. They can be helpful in some situations, but I tend to be a bit more DIY when it comes to PHP. It’s all a matter of personal preference, and of course choosing the right tool for the job.
If you have a bit of experience with PHP, it may be worth giving CodeIgniter a look.
Mar 26, 2009 by Matt | Posted in Coding
The Parse_URL function can dice a URL into individual segments for later usage.
Suppose you’ve just parsed a group of RSS feeds, and you’re looping through the results, displaying the ten most recent. You would like to put the items’ source domains under the headlines. You decide the best way to go about it is to take each item’s permalink or guid value and strip everything out of the URL but the domain.
Here’s an example of how to do that with Parse_URL:
$the_permalink = "http://www.webmaster-source.com/2009/03/21/blogbuzz-march-21-2009/";
$the_domain = parse_url($the_permalink, PHP_URL_HOST);
The script should output
www.webmaster-source.com. If you don’t pass the second argument, the function will return an associative array of all of the parts of the URL.
Mar 22, 2009 by Matt | Posted in Coding
If you’ve ever worked with WordPress’s “template tag” functions, you may have noticed that some of them take arguments in a strange way. Instead of passing arguments like
function($1, $2), they are handled much a URL query string, like
function('exclude=this&order=asc'). This enables you to pick and choose what arguments you want to specify, and the order in which you do so.
How is that done? I wondered about that myself for quite some time, but was too lazy to open the source code and see for myself. Recently I came across the PHP function that makes it possible: Parse_Str().
Take this code snippet for example:
Continue reading →
Mar 15, 2009 by Matt | Posted in Coding
Filter_Var() is a PHP function intended to help validate and sanitize certain types of data. It can verify that an email address is in a correct format, remove harmful characters and tags, etc..
I discovered this interesting feature through Sanitize and Validate Data with PHP Filters over at NETTUTS.
The function validates and sanitizes, two things that are very much different but easily confused. Validation is the act of making sure that input is formatted correctly, while sanitization is the process of filtering out unwanted garbage that may be detrimental, such as exploitation attempts.
The following would return a string containing the validated email, or FALSE if it were malformed.
Mar 12, 2009 by Matt | Posted in Coding
Caching dynamic content can save a lot of proceesing power, potentially saving a server from total meltdown under extremely high traffic loads. The popular WP Super Cache plugin has demonstrated this, helping blogs on small shared hosts survive the “Digg Effect” longer.
If a script’s output doesn’t change every time a page is loaded, does it need to be processed each time? Probably not. You can cache a page, or a section of a page, for an appropriate amount of time, and serve it up instead.
It’s a lot simpler to implement caching than you would think. It’s just a matter of using output buffering, a little bit of basic file I/O, and watching the server’s timestamp.
PaperMashup.com has a short article on how to apply a basic cache to your scripts.
It’s not a good idea to go away and cache your entire site, you need to think about which pages receive high traffic, and which pages make a number of database requests. Static HTML pages aren’t going to see a benefit from caching and may in fact be served slower due to PHP invoking the request to the cached version.
Mar 4, 2009 by Matt | Posted in Coding
Sometimes when you use SimplePie to load and output an RSS feed, some characters, like quote marks and apostrphes, are replaced with some gibberish like €‡™. You may wonder what’s wrong, and search to find a way to prevent the unsightly garbage from appearing.
You have an encoding issue.
RSS feeds are encoded as UTF-8, as are many web pages. If you try to put SimplePie output on a page that isn’t UTF-8, you’ll get the weird characters.
“But…my page is UTF-8! I have a
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> tag in my header!”
Actually, there’s more to it than that. In addition to specifying the
charset in your header, you server also has to send the data in UTF-8. If you use Firefox, choose Tools -> Page Info from the menu. In the resulting dialog box, note the two references to the encoding and charset.
Continue reading →
Mar 2, 2009 by Matt | Posted in Coding
DevTips has just introduced me, in a fairly recent article, to a PHP feature that I hadn’t been conciously aware of: Output Buffering. (Why hadn’t anybody told be about this before?)
Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script. Can you already begin to see the performance advantages and post processing opportunities?
The article covers the basic usage output buffering, and the pros and cons of using it. Definitely worth a look. I will have to look into this in depth sometime soon…
Output Buffering for Web Developers, a Beginner’s Guide