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'] : '');
  4.  
  5. // Input: https://browse-tutorials.com/äõö/encode?id=1
  6. // Output: https://browse-tutorials.com/%C3%A4%C3%B5%C3%B6/encode?id=1
Programming Language: PHP