10 PHP functions you (probably) never use

When scripting in PHP, we often restrict ourselves to a limited number of API functions: the common ones, like print(), header(), define(), isset(), htmlspecialchars(), etc. If some needed functionality doesn’t exist, we often write it making use of these basic components which we have in mind. The PHP API actually offers a lot of functionality, some useless and some useful; often seldom used. I have been looking through the available functions and was interested to find some really cool functions that I should have known about. Here, I share my findings.

1. sys_getloadavg()

sys_getloadvg() is a function which returns three samples of the “load” on a system. Load is the number of processes in the system run queue. The 3 items in the array are the average load for the past 1, 5 and 15 minutes. The PHP Manual shows a great usage of this:

$load = sys_getloadavg();
if ($load[0] > 80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}

Rather than have your web service become unavailable for everyone, you simply die when there’s too much load — primitively, this will allow some requests and deny others. The function will not work on Windows, though.

2. pack()

I actually use pack() fairly often, to make the 32-byte hexadecimal strings returned by md5() into 16-byte binary strings*:

$pass_hash = pack("H*", md5("my-password"));
$pass_hash = md5("my-password", true); // equivalent (PHP 5+)

It is very useful when storing data in databases; to save space. (In the case of packing hexadecimal values to binary strings).

3. cal_days_in_month()

cal_days_in_month() usefully returns the number of days in a given month:

$days = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y")); // 31
echo ( $days - date("d") + 1 ) . " days until " . date("F", mktime(0, 0, 0, date("m") + 1, 1, 1970));

4. _()

If you’ve developed for WordPress, you’ll know about the __() and _e() functions to make the software i18n-able. You can use gettext() (or _(), which is an alias), together with some other functions, to achieve the same functionality, in WordPress or not. This example was taken from the PHP Manual:

// Set language to German
setlocale(LC_ALL, 'de_DE');
 
// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");
 
// Choose domain
textdomain("myPHPApp");
 
echo _("Have a nice day");

You will need to build PHP with GNU gettext support. I suspect that there is a third-party solution out there which does the same thing, working on a standard installation. (Edit: in fact, there is — here; thanks Toni).

5. get_browser()

Wouldn’t it be nice to find out what a user’s browser could do before sending the page? Well, you can with get_browser(). You will need php_browscap.ini first, and point the browscap directive to the file. You could have something similar to this:

$browser = get_browser(null, true);
if(!$browser["frames"] || !$browser["cookies"])
  echo "Please download an up-to-date browser. Some sections of this site may be inaccessible";

This will not detect individual configurations of browsers, however; it can not be used to detect whether Javascript is enabled, for example. It may be useful to profile users — ie, by what browser and platform they use.

6. debug_print_backtrace()

It can be quite difficult to trace through code manually, particularly when looking for a logic error; after all, you wrote the logic! debug_print_backtrace() can get you out of a difficult situation. Here the function is being used to understand a rather pointless script:

$a = 0;
 
function iterate() {
	global $a;
	if( $a < 10 )
		recur();
	echo $a . ", ";
}
 
function recur() {
	global $a;
	$a++;
 
	// how did I get here?
	echo "\n\n\n";
	debug_print_backtrace();
 
	if( $a < 10 )
		iterate();
 
}
 
iterate();
 
# OUTPUT:

#0  recur() called at [C:\htdocs\php_stuff\index.php:8]
#1  iterate() called at [C:\htdocs\php_stuff\index.php:25]

#0  recur() called at [C:\htdocs\php_stuff\index.php:8]
#1  iterate() called at [C:\htdocs\php_stuff\index.php:21]
#2  recur() called at [C:\htdocs\php_stuff\index.php:8]
#3  iterate() called at [C:\htdocs\php_stuff\index.php:25]

#0  recur() called at [C:\htdocs\php_stuff\index.php:8]
#1  iterate() called at [C:\htdocs\php_stuff\index.php:21]
#2  recur() called at [C:\htdocs\php_stuff\index.php:8]
#3  iterate() called at [C:\htdocs\php_stuff\index.php:21]
#4  recur() called at [C:\htdocs\php_stuff\index.php:8]
#5  iterate() called at [C:\htdocs\php_stuff\index.php:25]

[...]

7. metaphone()

metaphone() is a function returning the same key for words which sound the same. soundex() does the same thing, but is less accurate (according to PHP Manual):

echo metaphone("train") . "\n"; // TRN
echo metaphone("terrain") . "\n"; // TRN
echo metaphone("not a train") . "\n"; // NTTRN
 
echo soundex("train") . "\n"; // T650
echo soundex("terrain") . "\n"; // T650
echo soundex("not a train"); // N336

8. natsort()

natsort() is a function which will sort items in an array naturally (ie, in an order which seems logical to a person), rather than by characters’ ordinal values. Take, for example:

$items = array(
	"100 apples", "5 apples", "110 apples", "55 apples"
	);
 
// normal sorting:
sort($items);
print_r($items);
# Outputs:
# Array
# (
#     [0] => 100 apples
#     [1] => 110 apples
#     [2] => 5 apples
#     [3] => 55 apples
# )

natsort($items);
print_r($items);
# Outputs:
# Array
# (
#     [2] => 5 apples
#     [3] => 55 apples
#     [0] => 100 apples
#     [1] => 110 apples
# )

9. levenshtein()

levenshtein() tells you how “far” away two words are. It will return the minimum number of inserts, replaces and deletions needed to transform one string to the other. Take, for example, the following code:

$dictionary = array(
		"php", "javascript", "css"
	);
 
$word = "japhp";
 
$best_match = $dictionary[0];
$match_value = levenshtein($dictionary[0], $word);
 
foreach($dictionary as $w) {
	$value = levenshtein($word, $w);
	if( $value < $match_value ) {
		$best_match = $w;
		$match_value = $value;
	}
}
 
echo "Did you mean the '$best_match' category?";

In this case, the user has been asked to provide a category name. They provided “japhp”, which is invalid. Since this is likely to be a typing error, the code above will make a suggestion (“Did you mean the ‘php’ category?”).

10. glob()

glob() will make you feel stupid after using opendir(), readdir() and closedir() to search for a file. It’s this simple:

foreach (glob("*.php") as $file)
    echo "$file\n";

Any more?

There are loads of functions out there. If you can’t get enough, http_build_query(), register_shutdown_function() and pspell_suggest are also worth a mention.What’s your favourite discovery?

Related Posts with Thumbnails

Advertisements:

You can follow any responses to this entry through the RSS 2.0 feed.

Comments

  1. On August 26, 2009 Rob says:

    Excellent info, Thanks guys

  2. On August 28, 2009 Dominik says:

    Really useful! Thanks!

  3. On September 04, 2009 Brandon Hansen says:

    Nice! I really appreciated the “sys_getloadavg()” method. That method is a server-saver for ajax applications.

  4. On September 05, 2009 MilitarySmurf says:

    cal_days_in_month() probably does the same thing as date(‘j’);

  5. On September 05, 2009 Brendon says:

    @MilitarySmurf, date(“j”) will not do it, but it seems date(“t”) will for the current month. You could of course further this with date(“t”, mktime(0, 0, 1, $month, 1, $year)) for any month. For me, I would use cal_days_in_month() for it’s semantic quality although the two do exactly the same thing.

    Thanks,
    Brendon.

  6. On November 23, 2009 Matt says:

    The gettext() link points to the cal_days_in_month() function. Other than that I hated your article as it is giving away how the pro’s make their websites better than the amateurs. You should stop writing useful articles :)

  7. [...] 10 PHP functions you (probably) never use. [...]

  8. On January 12, 2010 Can Berkol says:

    I actually use some of those quite often :) .

  9. On January 12, 2010 peace4men says:

    Very interesting !
    I try to use some of the functions on my next works ;)

  10. On January 12, 2010 alvaroveliz says:

    I’ve only used two a couple of functions from the list. Thank you very much for making me feel more useless reinventing the wheel :(
    Excellent info btw!

  11. On January 12, 2010 Davidmoreen says:

    I only knew one, natsort()! I need to get on my A game.

  12. On January 12, 2010 JMLeon says:

    Thanks for glob(). Ii feel terribly stupid.

  13. On January 12, 2010 Joel says:

    Hah, I thought it said “10 PHP functions you should probably never use” at first.

    No, seriously? A PHP function that tests how words sound?

  14. On January 12, 2010 Silence says:

    Very nice article! Thank you.

    I thought -by example- that “Did you mean the ‘$best_match’ category?” function of google or other applications was very hard to do

    Regards

  15. On January 12, 2010 download youtube says:

    Not only are rare also very useful…thanks :)

  16. On January 12, 2010 Alex says:

    Damn it! I used usort() a few months ago to do what natsort() does!

  17. On January 13, 2010 Ricardo Pedrosa says:

    LOL

    levenshtein() is used to “did you mean”

  18. [...] more… [...]

  19. On January 13, 2010 Pritush says:

    in this list the only function i have heard of or use is
    5.g et_browser()

  20. On January 13, 2010 Chris says:

    Nice post, I haven’t really heard about some of these functions. :-)

  21. On January 13, 2010 Satya Prakash says:

    levenshtein() is very new to me

  22. On January 13, 2010 Matt Lowden says:

    I feel bad knowing barely half of these functions.

    debug_print_backtrace and sys_getloadavg seem especially useful.

    Great post..

    Matt.

  23. On January 13, 2010 bds says:

    levenshtein() is not used for “did you mean” by Google. They have statistics on what people type after they have misspelled. With the huge amount of data they have it’s much faster and efficient way to get the wanted result.

  24. On January 13, 2010 Neel says:

    Yes, very useful tips.

  25. [...] @smashingmag encontré en Infinity-Infinity el artículo 10 PHP functions you (probably) never use, una recopilación de diez funciones de PHP de uso poco o nada frecuente  que yo reduzco a [...]

  26. On January 13, 2010 digitalpbk says:

    Nice post, Thanx for the GLOB :)

  27. On January 13, 2010 abcphp.com says:

    10 PHP functions you (probably) never use…

    When scripting in PHP, we often restrict ourselves to a limited number of API functions: the common ones, like print(), header(), define(), isset(), htmlspecialchars(), etc. If some needed functionality doesn’t exist, we often write it making use of th…

  28. On January 13, 2010 links for 2010-01-13 says:

    [...] 10 PHP functions you (probably) never use (tags: development webdesign php tips) Socio-Encapsule this: [...]

  29. On January 13, 2010 Chris says:

    The funny thing is a while back I wrote a blog post about how to get the number of days in a month with PHP. When I read this article I thought, “oh why didn’t I know about the cal_days_in_month() function when I wrote it. Better go back and update it to show that function.” So I went back to revise my post and sure enough I had actually blogged about the cal_days_in_month() function. It’s funny how you can even know about some of these functions and still forget about them. Thanks for reminding me about this useful function yet again :)

  30. On January 14, 2010 EllisGL says:

    I was wondering wth #4 was the other day.
    #5 has a bug in 5.3.1 at the moment.. You can’t pass null.. =( Next release it will be fixed.
    I’ve used #8 and #10
    #3 good one to know (tries to store it for later usauge)

  31. On January 14, 2010 Suits says:

    Some I knew of and now I am going to take advantage of the rest. I still have an issue with requiring someone to read my code with a function _() and then someone makes __() which suits him better and then we are dealing with code __-___() which doesn’t work with humans!

  32. On January 14, 2010 hun chang says:

    omg what an ugly language. look at those function names! cal_days_in_month() is the worst.

  33. On January 14, 2010 Shawn says:

    I wrote a bit about metaphone before: http://www.unemployeddeveloper.com/315_lesser-known-php-functions-%E2%80%93metaphone/

  34. On January 14, 2010 Toni says:

    for php gettext you can use https://launchpad.net/php-gettext/ implementation on server without gettext builded

  35. [...] full post on Hacker News If you enjoyed this article, please consider sharing it! Tagged with: functions [...]

  36. On January 14, 2010 Robin says:

    Just some heads up for the author of the article:

    md5() has a second, optional parameter. If you set this to true, the output will be 16 bytes of “raw, binary” checksum, instead of a string of hexits, thus you have no need to go about it the clumsy “pack()” way (unless you live on a server from the past). This option has been available since php 5.0.0, released summer 2004.

    $raw = md5( $data, true );

    YOU’RE WELCOME!

  37. [...] Shared 10 PHP functions you (probably) never use. [...]

  38. On January 14, 2010 henk says:

    Actually i’ve already used em all!

    great funtions

  39. On January 14, 2010 tback says:

    regarding 2) Don’t forget to salt the password before you hash it.
    $salt = some_random_bytes(); // _really_ random
    $limit_char = ':' ; //some character that doesn't occur in the other strings
    $hash = md5( $some_random_salt + $password );

    // now store this in your db like this (and pack it if you want to):
    $store = $salt + $limit_char + "md5" + $limit_char + $hash;

    //now verify $given_password like this:
    $a = split($limit_char,$store,3);
    $salt = $a[0]; $hash_type=$a[1]; $hash = $a[2];

    assert($hash_type=="md5"); // this will allow you to use other hash functions in the future
    if( md5( $salt + $given_password ) == $hash ){
    huzzaaah('let user in');
    }
    // didn't test the code, just wrote it down

  40. On January 14, 2010 Nikolaos Dimopoulos says:

    Thank you for this resource. As a matter of fact I have used quite a few of the functions in your list but I admit this is the first time I hear of metaphone and levenshtein.

    Thank you again!

  41. On January 14, 2010 Rob Sayers says:

    I’ve seen a lot of posts with similar titles, this is hte first one I’ve seen which was true. Cheers.

  42. On January 14, 2010 Brendon says:

    @Robin,

    Thanks; that was mentioned in the example given. Does anybody have any suggestions for other pack()-usage?

    Thanks,
    Brendon.

  43. On January 14, 2010 Yep says:

    Says the man with the most grammatically beautiful comment.

  44. On January 14, 2010 nurv7 says:

    nice articles…i used Codeigniter but this is my first time ive heard those functions.

  45. On January 14, 2010 bumpkinplusplus says:

    Oddly enough, I actually use glob() from time to time. It came in handy when I was creating a photo gallery page that I wanted to make it relatively easy to update without making it database-driven. All I had to was prefix the images a certain way and bada-bing!

    Anyway, great article. I especially dig the one that lets you see the function call stack.

  46. On January 14, 2010 jesus gabriel vazquez canche says:

    interesting and beatifull I will used something

  47. On January 14, 2010 1024 says:

    I once wanted to do a “did you mean”, so I wasted an hour trying to code the Levenshtein distance algorythm. Then I gave up and Googled “php Levenshtein”. Imagine how I felt at that moment :D

  48. [...] 10 PHP functions you (probably) never use » » [...]

  49. [...] 10 PHP functions you (probably) never use [...]

  50. [...] 10 PHP functions you (probably) never use [...]

  51. [...] from his blog Brendon has a list of what he thinks are ten PHP functions you’ll never use. When scripting in PHP, we often restrict ourselves to a limited number of API functions: the [...]

  52. On January 15, 2010 Greg says:

    I use pack() and unpack() on a bot to handle the binary server format of a open source MORPG. Works nicely.

  53. On January 16, 2010 Luiz Fernando says:

    With glob you can find files inside unknown folders:

    foreach (glob(“\extensions\*\ext.php”) as $file)
    echo “$file\n”;

  54. [...] in 20 Years – DCS Media Nummer 8 sollte auf dem Kopf jedes Managers tatowiert werden 10 PHP functions you (probably) never use 10 Selten genutzte PHP-Funktionen, die man nicht vergessen sollte. Technology Review | 14.01.10 | [...]

  55. On January 16, 2010 superdick says:

    From the comments I start to see why Php developers are so low regarded
    No really, you have never heard – not to mention used – about these functions ?
    Just take the Php manual and read it from cover to cover like 10 times or so then have the guts to consider yourself PHP programmers

  56. On January 16, 2010 Language gems | Aaron Falloon says:

    [...] article on seldom used PHP functions made its way into my feed reader. It’s a useful resource and has made me wonder what other [...]

  57. [...] Shared 10 PHP functions you (probably) never use. [...]

  58. On January 16, 2010 p4on says:

    Nice one thx

  59. On January 16, 2010 Neil Nand says:

    That’s a lot that natsort() function I’ll be using really soon

  60. [...] 10 PHP functions you (probably) never use [...]

  61. On January 17, 2010 Linkhub Woche 03-2010 - pehbehbeh says:

    [...] 10 PHP functions (probably) never use [...]

  62. On January 17, 2010 Waleed Gadelkareem says:

    really helped..thanks a lot!

  63. On January 18, 2010 Amatoc Industries says:

    Thanks for this post. I knew some of these, but had forgotten about them, and some of these are very new to me. Great information and i’ve gotten some ideas for my websites from these

  64. On January 18, 2010 Erik says:

    I totally agree with Matt. Nuff said. :P

  65. [...] L’articolo in questione si trova in questo blog all’indirizzo: http://infinity-infinity.com/2009/07/10-php-functions-you-probably-never-use/ [...]

  66. [...]  10 PHP functions you (probably) never use (0 visite) [...]

  67. [...] Brendom, do blog Infinity-Infinity, fez uma lista de 10 funções que você provavelmente nunca usou, mas podem ser úteis quando [...]

  68. [...] 10 PHP functions you (probably) never use – When scripting in PHP, we often restrict ourselves to a limited number of API functions: the common ones, like print(), header(), define(), isset(), htmlspecialchars(), etc. If some needed functionality doesn’t exist, we often write it making use of these basic components which we have in mind. The PHP API actually offers a lot of functionality, some useless and some useful; often seldom used. I have been looking through the available functions and was interested to find some really cool functions that I should have known about. Here, I share my findings. [...]

  69. [...] script php facile à appliquer et pratique (pour les graphistes). J’ai trouvé ce bout de php ici, il affiche la liste des fichiers php présents dans un dossier foreach (glob("*.php") as $file) [...]

  70. [...] 10 PHP functions you (probably) never use (tags: WebDev PHP Programming Development tips Lists) [...]

  71. On January 21, 2010 Sam says:

    great i will put it in my own website wladelnil.com

  72. On January 23, 2010 Mingo Max says:

    Hi, its very interesting, but some function i was used in my projects!!
    But really, this functions are nothing come used!!!!

    great!

  73. On January 28, 2010 Linkee.Fr says:

    Nice article, actually i learned 10 functions reading this article, they are all very useful and sure i’ll will use them in my future works :-)

    linkee.fr

  74. On January 30, 2010 devnotes says:

    thanks for info, glob() is awesome :)

  75. On February 01, 2010 security war says:

    very useful keep on man

  76. On February 03, 2010 Mohammed Ameenuddin Atif says:

    For the first time in months, I felt like commenting on a blog and thanking you for this.

    Great post! The first function was really helpful for me

  77. On February 04, 2010 Mohammed Ameenuddin Atif says:

    Lol another one is file_get_contents() and file_put_contents()
    I never knew about them till today

  78. On February 09, 2010 Dave says:

    great list,,, never knew about 70% of these

  79. On February 26, 2010 Novalja says:

    thats true i never used one of them. great list

  80. On March 07, 2010 You are now listed on FAQPAL says:

    10 PHP functions you (probably) never use…

    I have been looking through the available functions and was interested to find some really cool functions that I should have known about. Here, I share my findings….

  81. On March 13, 2010 markowe says:

    ha, I had heard of them all, but only because I recently did what someone politely suggested above: read the entire PHP manual. But PHP is a great language for getting straight into web scripting without much effort, so people often stick with the basic functions that they know, you DON’Thave to be a hotshot PHP coder who’s read all the books and done all the courses, it’s a nice gradual learning slope.

  82. On March 14, 2010 Ceina Nunes says:

    I actually use metaphone on my website http://www.anuglymind.co.uk which generates poetry. It is a very useful command and I believe is unique to PHP…?

  83. [...] 10 PHP functions you (probably) never use – When scripting in PHP, we often restrict ourselves to a limited number of API functions: the common ones, like print(), header(), define(), isset(), htmlspecialchars(), etc. If some needed functionality doesn’t exist, we often write it making use of these basic components which we have in mind. The PHP API actually offers a lot of functionality, some useless and some useful; often seldom used. I have been looking through the available functions and was interested to find some really cool functions that I should have known about. Here, I share my findings. [...]

  84. On March 26, 2010 Adam says:

    This is brilliant! True beauty is simple, as you have just proved right here. Now I love PHP even more, thanks!

  85. [...] dem hier und hier die PHP Funktion glob() als besonders revolutionär bzw. exotisch hervorgehoben wurde, muss ich [...]

  86. On May 16, 2010 Tereza says:

    This is very useful!

  87. On May 21, 2010 Harsha M V says:

    nice to learn a few new functions which would make life easier

  88. On August 15, 2010 X3noph0n says:

    Excellent article !
    keep going ;)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">