10 things you (probably) didn’t know about PHP.

PHP is simultaneously the most infuriating and joyful languages I’ve ever worked with. I say “infuriating” primarily because the function names are so inconsistant. Despite the fact that I use it almost everyday, I still have to think to myself “Is it str_pos or strpos? str_split or strsplit?” On the other hand, occasionally I’ll stumble across a gem that perfectly solves the problem at hand with a single line of code.

Here’s a short list of cool features that might have slipped under your radar as well:

  1. Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit).
  2. Partially validate email addresses by checking that the domain name exists with checkdnsrr(). This built-in function checks to ensure that a specified domain name resolves to an IP address. A simple user-defined function that builds on checkdnsrr() to partially valid email addresses can be found in the user comments section in the PHP docs. This is handy for catching those occasional folks who think their email address is ‘joeuser@wwwphp.net’ instead of ‘joeuser@php.net’.
  3. If you’re using PHP 5 with MySQL 4.1 or above, consider ditching the mysql_* functions for the improved mysqli_* functions. One nice feature is that you can use prepared statements, which may speed up queries if you maintain a database-intensive website. Some benchmarks.
  4. Learn to love the ternary operator.
  5. If you get the feeling that you might be reinventing the wheel during a project, check PEAR before you write another line. PEAR is a great resource that many PHP developers are aware of, yet many more are not. It’s an online repository containing over 400 reusable snippets that can be dropped right into your PHP application. Unless your project is trully unique, you ought to be able to find a PEAR package that saves at least a little time. (Also see PECL)
  6. Automatically print a nicely formatted copy of a page’s source code with highlight_file().This function is handy for when you need to ask for some assistance with a script in a messageboard, IRC, etc. Obviously, some care must be taken not to accidently show your source when it contains DB connection information, passwords, etc.
  7. Prevent potentially sensitive error messages from being shown to users with the error_reporting(0) function. Ideally error reporting should be completely disabled on a production server from within php.ini. However if you’re on a shared webhost and you aren’t given your own php.ini, then your best bet is to add error_reporting(0); as the first line in each of your scripts (or use it with require_once().) This will prevent potentially sensitive SQL queries and path names from being displayed if things go awry.
  8. Use gzcompress() and gzuncompress() to transparently compress/decompress large strings before storing them in a database. These built-in functions use the gzip algorithm and can compress plaintext up to 90%. I use these functions almost everytime I read/write to a BLOB field within PHP. The only exception is when I need full text indexing capabilities.
  9. Return multiple values from a function with “by reference” parameters. Like the ternary operator, most PHP developers who come from a more formalized programming background already know this one. However, those who’s background is more HTML than Pascal, probably have wondered at one time “how do I get multiple values back from a function I wrote, even though I can only use one return value?” The answer is that you precede a variable with “&” and use it “by reference” instead of “by value”.
  10. Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it’s absolutely critical to understand. If you’ve never heard the term before, spend the entire rest of the day googling and reading.

84 Comments

Leave a comment
  1. mike 18. Aug, 2007 at 1:34 pm #

    If you have to worry about number 8, then find a new database.

  2. Tom 18. Aug, 2007 at 2:16 pm #

    Uhh… #2 is wrong.

    The domain in an email address does not need to resolve to an IP to be valid. An e-mail address domain can be perfectly good without an IP address, so if you follow this “tip” you will reject some perfectly good e-mail addresses.

    To properly validate the domain in an e-mail, you must do an MX record lookup.

  3. Jhecht 18. Aug, 2007 at 7:38 pm #

    Only problem with checkdnsr is that its an apache pacific function. So if you are like most, and first create your code on Windows and then upload it to an apache server, it doesn’t work on your test server so you can never tell what will happen.

  4. Rafael S. Souza 22. Aug, 2007 at 6:12 am #

    “Learn to love the ternary operator.”

    Too much love can be a problem. ;)

    Cheers

  5. Vincenzo 19. Dec, 2007 at 12:07 am #

    Why only 10 things?
    2. I would check for MX, A, CNAME entries for a host
    3. I think it’s better to use PDO now if you want to make your code database-independent to some extent.

  6. Tim 23. Jan, 2008 at 12:08 pm #

    I’m still learning PHP, but I’ve already come to love the ternary operator for simple (non-nested) assignments…it keeps code simpler and less visually jarring. To help visually parse the ternary statement, however, I place parens around each of the pieces, like so:

    $var = (testvalue) ? (truevalue) : (falsevalue);

    which makes it quite easy to read.

Trackbacks/Pingbacks

  1. SitePoint Blogs » Sep 20, 2006 News Wire - 20. Sep, 2006

    [...] 10 things you (probably) didn’t know about PHP A few obvious items in this list, but a number of gems too. Even PHP experts should take a quick look—there might just be a valuable feature or two you didn’t know about! (tags: php) [...]

  2. PHP碎语 / PHP你所不知道的10件事 - 22. Oct, 2006

    [...] 本文翻译自10 things you (probably) didn’t know about PHP。翻译有什么不正确的地方,请读者斧正。转载本文请注明出处,谢谢! [...]

  3. PHPGeek » 10 Things You Probably Didn’t Know About PHP - 25. Oct, 2006

    [...] Given how many people teach themselves PHP via tutorials, articles, books, and just plain messing around, it’s easy to end up with gaps in your knowledge. That’s why I always like lists like the 10 Things You Probably Didn’t Know About PHP. [...]

  4. meneame.net - 26. Oct, 2006

    10 cosas que (probablemente) no conozcas de PHP

    Artículo muy interesante se nos explican 10 sencillas mejoras que podemos introducir en nuestra programación PHP para hacerla más rápida y segura. Muy útil el artículo si programas en PHP, yo diría que de lectura obligada. Por cierto está en in…

  5. 10 PHP tips - alexmoskalyukblog - 27. Oct, 2006

    [...] There’s a pretty good quick list of 10 PHP tips from yet another Web development blog. [...]

  6. links for 2006-10-28 | Musings by Steve Miller - 28. Oct, 2006

    [...] Yet Another Web Development Blog » 10 things you (probably) didn’t know about PHP. (tags: php Programming tips development webdev web php5) [...]

  7. Linky na víkend 32 na depi.sk - IT & Life Weblog - 28. Oct, 2006

    [...] 10 things you (probably) didn’t know about PHP – 10 vecí, ktoré (pravdepodobne) neviete o PHP [...]

  8. davidbisset.com » 10 things you (probably) didn’t know about PHP - 28. Oct, 2006

    [...] A few nice mysql and php tips in here. [...]

  9. warpedvisions.org » Blog Archive » Some good Php tips - 28. Oct, 2006

    [...] October 28th, 2006 in Links 10 things you probably didn’t know about Php, even including a few things I didn’t know. Be sure to read the comments (a few of the tips are incomplete). [...]

  10. imagesafari blog » Blog Archive » 10 things you (probably) didn’t know about PHP. - 31. Oct, 2006

    [...] Link [...]

  11. links for 2006-10-28 at willkoca - 31. Oct, 2006

    [...] Yet Another Web Development Blog » 10 things you (probably) didn’t know about PHP. (tags: php programming) [...]

  12. 6 cosas que probablemente no conozcas sobre PHP « Juan Jorquera Blog - 04. Nov, 2006

    [...] Vía: 10 things you (probably) didn’t know about PHP [...]

  13. blog.code.ae » Blog Archive » PHP coding tips - 06. Nov, 2006

    [...] Both this link and this link give PHP coders some tips in making faster and better PHP web applications. [...]

  14. Filter for 30/10 2006 - Felt - 10. Nov, 2006

    [...] 10 things you (probably) didn’t know about PHP. You’re right, I didn’t. [...]

  15. Data Circle » Blog Archive » Ten things you might not know about PHP - 17. Nov, 2006

    [...] 10 things you (probably) didn’t know about PHP [...]

  16. Links comentados via del.icio.us - 7 » Japs - 19. Nov, 2006

    [...] A quarta parte de hoje são alguns links sobre desenvolvimento: Controle de sessão e PHP, Modelo de orientação a objetos em PHP 5, Minikit: visual effect bag, Sugar Arrays: Porting over JavaScript 1.6 Array methods, Remote Scripting Transport Patent, Amberjack: JavaScript Site Tour Creator, 3D Rendering in JavaScript e 10 things you (probably) didn’t know about PHP. [...]

  17. 10 dicas para PHP « Vômito Blog - AJAX, Php, Delphi, J2ME, etc. - 21. Nov, 2006

    [...] 10 things you (probably) didn’t know about PHP. [...]

  18. » Funções do PHP para trabalhar com IP - 19. Dec, 2006

    [...] Para finalizar. Conheci a função ip2long() e long2ip neste post: 10 things you (probably) didn’t know about PHP e cheguei até ele através deste outro: Links comentados via del.icio.us – 7 [...]

  19. turkiyelim.ath.cx » 10 things you (probably) didn’t know about PHP. - 26. Jan, 2007

    [...] Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit). [...]

  20. » Otimização de códigos PHP: Links - 04. Feb, 2007

    [...] 10 things you (probably) didn’t know about PHP [...]

  21. Myglobalblog » Blog Archive » life is about PHP - 14. Feb, 2007

    [...] Url.Site.PHP.ten things about PHP you might not have known and that are worthy to know and use [...]

  22. Enakans Blog - 30. Mar, 2007

    [...] ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage [...]

  23. .:: enakans dot com ::. - 31. Mar, 2007

    [...] ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage [...]

  24. .:: enakans blog ::. - 13. Apr, 2007

    [...] ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage [...]

  25. =- AltF4 -= | - » Blog Archive » Funções do PHP para trabalhar com IP - 25. Jul, 2007

    [...] Para finalizar. Conheci a função ip2long() e long2ip neste post: 10 things you (probably) didn’t know about PHP [...]

  26. Tips & Tricks : Prototype, ChartDirector, Tabber, ViM et PHP - Le tipi de Tothem - 20. Aug, 2007

    [...] Quelques fonctions PHP qui pourraient être utiles à certain(e)s Ten things you probably didn’t know about PHP Cool things about PHP that most people [...]

  27. My Bookmarks - Design « يادآفرين - 05. Sep, 2007

    [...] Yet Another Web Development Blog » 10 things you (probably) didn’t know about PHP. [...]

  28. rtraction » Blog Archive » 10 things you (probably) didn’t know about php - 08. Sep, 2007

    [...] Check out the rest here: 10 things you (probably) didn’t know about php [...]