Vince Rants

Please Don't printf() in PHP

This is a short, sweet, simple, and right to the point rant.

Please don't use the printf() function in PHP unless you absolutely know what you're doing.

A trend I've been seeing lately by novice developers in various PHP communities is to use printf instead of echo or print

But why? What is the difference?

First and foremost, echo and print are language constructs, whereas printf is a function. This honestly doesn't mean much other than for subtle ways they can be interacted with. All three push content from the server to the client.

The fundamental difference is the f in printf. The f stands for "formatted" string. There are two very important parts to this.

1) printf expects the first argument to the function to be a string. I'm seeing novice developers pass in other variable types to this function, which is flat out against spec, and is only "working" because of the implicit type conversion to string. This means if you're working with an integer, PHP will internally convert it to a string when calling this function.

2) The elephant in the room. The function printf doesn't just take in any old string; it only takes in special "formatted" strings. If care is not taken with these specially formatted strings, it can very easily lead to unintended bugs or even security exploitation.

In other words, unlike echo and print, the printf function will modify the contents of the string based on formatting parameters before passing it along from the web server to the browser client. If you're not aware of these string transformations, you're in for a world of hurt!

For further reading, please consult the PHP manual:

A small practical example:

<?php echo("%d\n"); print("%d\n"); printf("%d\n"); echo "\n-- %s --\n", "test\n"; printf("\n++ %s ++\n", "test\n");

This code will output the following:

%d %d Warning: printf(): Too few arguments in /in/khEVC on line 4 -- %s -- test ++ test ++