5 PHP Mistakes and How to Avoid Them

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.