Why you should use the PHP function “sprintf()”

Why you should use the PHP function “sprintf()”

Here at WP-translations our first concern is translation of course but it doesn’t mean it’s our only one. Something we’re really concerned about is Security.

And so as a responsible community we wanted to take 5 min to talk about security in WordPress translations strings.

WordPress embeds really neat functions, like the wp_sprintf() functions but sometimes you as developers aren’t aware of them and you don’t realize what you’re living in the open in your code. Open source doesn’t mean open breach.

Today we’ll stop on a basic PHP function : the sprintf() function.

Let’s take a really simple example: Something we usually see and that we shouldn’t in translations strings looks like that:

[gist url=”https://gist.github.com/fxbenard/7007385″ file=”no-sprintf.php”]

Don’t you see something wrong here? You’ll tell me, ok it’s just an url, no worries, but can you imagine what happens if someone decides to change the url to another one in your translation, will you notice it, i guess not!

To prevent such issue we started at WP-Translations building a system of dedicated reviewers, people who makes sure everything is setup right and not changed, but even with our best wishes the most efficient way is YOU as a coder. 

That’s why we encourage you to always use the power of the sprintf() function everywhere in your code.

The previous piece of code will then look like that and nobody can “mess” with any urls anymore.

[gist url=”https://gist.github.com/fxbenard/7007385″ file=”I-luv-my-sprintf.php”]

You’ll notice we also added the esc_url function in the code, which is also a good practice, but we’ll talk about that in another post.

And if you want to learn more about i18n in WordPress, only one place the Codex.

Are you convinced now why you should use the WordPress function “sprintf” in your code? Are you already using it? Let us know and share your best practice!

3 Comments

    1. FxB

      Yes sorry if i used the php function instead of the WordPress wp_sprintf() function. I was taking at the code level and not the core level, i’ll update my post, thanks to you and to @Mamaduka for pointing that out.

Leave a Reply

Your email address will not be published. Required fields are marked *