You are here

23 May 2017

This snippet encodes urls for curl. If you use special letters like äõöü in url, then you get a bit different url parsing from browsers than curl in PHP. You would think that you could use php's own encode functions, but you can't since they encode all slashes and all parts of the url. When you need to encode only between the slashes, this is perfect for you. If you might have special letters in query parameters, then you have to modify the script a bit. The script takes the url appart and uses encode on path part only. Then the url gets reassembled.

Source code viewer
  1. $parsed = parse_url($remote);
  2. $parsed['path'] = implode('/', array_map('rawurlencode', explode('/', $parsed['path'])));
  3. $remote = $parsed['scheme'] . '://' . $parsed['host'] . $parsed['path'] . (isset($parsed['query']) ? '?' . $parsed['query'] : '');
  5. // Input:äõö/encode?id=1
  6. // Output:
Programming Language: PHP