WordPress / WordPress/WordPress-Coding-Standards

Allow (s)printf to be used for sanitising/escaping

Open
#1,870 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Component: Extra Focus: Security Type: Enhancement
Dominant language
PHP
Stars
2.8k
Forks
521
Avg merge
5d 20h
Merged PRs (30d)
1

Description

Is your feature request related to a problem?

Yes. When writing code like the following, it's flagged as unescaped (WordPress.Security.EscapeOutput.OutputNotEscaped):

printf(
    'Foo %d Bar',
    $id
);

With some string formats, the format itself can provide adequate sanitising/escaping support. Specifically, any format which does not treat the input as a string: b, c, d, o, u, x, and X all treat the input as an integer, while e, E, f, F, g, and G treat the input as a double (eg float).

Essentially, only %s is unsafe for use printf for arbitrary variables, as all the others have the effect of typecasting to a number.

In practice, this only really matters for the EscapeOutput sniff with printf, but in theory, sprintf can actually be used as a sanitisation function as well; sprintf( '%d', $foo ) is a (weird) way to sanitise inputs into integer strings. (I've never seen this in practice though.)

Describe the solution you'd like

printf should be allowed to output input variables with any non-%s specifier without requiring unneeded escaping.

The following code should pass:

printf( 'Comment count: %d', $comment_count );
printf( 'Request time: %.4f', microtime( true ) );

(etc)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue does not name files or tests; start by locating the WordPress.Security.EscapeOutput.OutputNotEscaped sniff and its handling of printf and sprintf. Review how format specifiers are classified, then verify that the integer and float examples pass while %s input still requires escaping.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.