A URL should be properly encoded to deal with spaces when passed to file_get_contents
, but there appears to be a strange inconsistency in behaviour (accidentally discovered) when not doing so that I'm curious about.
Here we see a 400 bad request when the space is not encoded:
$ php -r "echo file_get_contents('https://api.postcodes.io/postcodes/Willoughby Hedge/validate');"
PHP Warning: file_get_contents(https://api.postcodes.io/postcodes/Willoughby Hedge/validate): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in Command line code on line 1
PHP Stack trace:
PHP 1. {main}() Command line code:0
PHP 2. file_get_contents($filename = 'https://api.postcodes.io/postcodes/Willoughby Hedge/validate') Command line code:1
If we encode it, it works as you would expect:
$ php -r "echo file_get_contents('https://api.postcodes.io/postcodes/Willoughby%20Hedge/validate');"
{"status":200,"result":false}
So why does this also work, without the encoding of the space?
$ php -r "echo file_get_contents('https://api.postcodes.io/postcodes/Willoughby hedge/validate');"
{"status":200,"result":false}
Note the "H" in "Hedge" is now "h" but we didn't encode the space. Curiously, if you substitute "H" for another letter such as "Z", it will also work.
Is there something specifically going on with a space and then a "H" in the function?
This is testing with PHP 8.1.