Opened 3 months ago
Last modified 3 months ago
#23605 new defect (bug)
esc_url() strips spaces instead of encoding them
| Reported by: |
|
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)
comment:1
SergeyBiryukov — 3 months ago
comment:2
bananastalktome — 3 months ago
- 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)?
comment:3
SergeyBiryukov — 3 months ago
test_spaces() was originally added in [226/tests], modified in [229/tests] and [273/tests].
comment:4
jscampbell.05 — 3 months ago
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.
comment:6
jscampbell.05 — 3 months ago
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.
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.
comment:8
jscampbell.05 — 3 months ago
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.

Also noted in ticket:21749:2.