Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What could the purpose of replacing %20 with spaces before doing PHP rawurlencode() be?

Tags:

php

urlencode

It's a pretty silly question, sorry. There is a big and rather complex system that has a bug and I managed to track it down to this piece

return str_replace('%2F', '/', rawurlencode(str_replace('%20', ' ', $key)));

There is a comment explaining why slashes are replaced - to preserve path structure, e.g. encoded1/encoded2/etc. However there is no explanation whatsoever why %20 is replaced with space and that part is the direct cause of a bug. I am tempted to just remove str_replace() but it looks like it was placed there for some reason and I have a feeling that I'll break something else by doing this. Has anyone encountered anything similar? Perhaps it's a dirty fix for some PHP bug? Any guesses and insights are highly appreciated!

like image 208
Eugene Avatar asked Dec 06 '25 08:12

Eugene


1 Answers

Doing so would prevent %20 (encoded space) from being encoded to %2F20. However, it only serves to prevent double escaped spaces; other special characters would still get double encoded.

This is a sign of bad code; strings that are passed into this function shouldn't be allowed to have encoded characters in the first place.

I would recommend creating unit tests that cover all referencing code and then refactor this function to remove the str_replace() to make sure it doesn't break the tests.

like image 70
Ja͢ck Avatar answered Dec 07 '25 20:12

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!