Opened 3 months ago

Last modified 3 months ago

#23605 new defect (bug)

esc_url() strips spaces instead of encoding them

Reported by: johnbillion Owned by:
Priority: normal Milestone: Awaiting Review
Component: Formatting Version:
Severity: normal Keywords:
Cc: bananastalktome@…

Description

If I pass a URL into esc_url() that contains a space, the space is stripped instead of encoded.

To reproduce:

$url = 'http://example.com/foo bar/';

echo '<pre>';
var_dump( $url );
var_dump( esc_url( $url ) );
echo '</pre>';

The resulting URL ends up as http://example.com/foobar/ instead of the expected http://example.com/foo%20bar/

Change History (8)

  • Cc bananastalktome@… added

The stripping spaces behavior is actually reflected in the unit tests, according to the test at source:trunk/tests/formatting/EscUrl.php@1219#L8, it seems originally added in [UT331]. Seems unusual, and I wonder if the test should be changed to reflect the desired behavior instead (encoding spaces)?

test_spaces() was originally added in [226/tests], modified in [229/tests] and [273/tests].

I would quite like this fixed as it is driving me mad, I have resorted for the moment using a str_replace on the string in a custom function I wrote.

My function goes like this:

function jc_encode_spaces($string){
    return str_replace(' ', '%20', $string);
}

Not Idea but it does the job

Space is an invalid character in URLs, so it should be escaped just like any other invalid character. Stripping them is absolutely the wrong thing to do.

Yes but when I use any URLs with wordpress I need them to be turned into 20% which is valid but it dosn't do that so I've had to manually do that using my function above.

Version 0, edited 3 months ago by jscampbell.05 (next)

Aren't we mixing up escaping for display and actual encoding here? PHPDoc for esc_url() does indicate that it removes characters, not encodes them. Seems like there are any number of characters that are stripped rather than encoded, not just spaces, for what it's worth.

Is there actually a away to encode spaces ? i.e " " becomes %20. I must say I expect most of the URI based functions to do this and not to simply strip away the spaces so they don't point to the correct resource.

Note: See TracTickets for help on using tickets.