paths

Passing urls as path arguments in urls

Sometimes you want to pass a url as a path argument. Drupal explodes urls by slash (/) to get the separate "arguments". Since the passed url probably also contains slashes, this will give erroneous results.

Using the following functions (compress_string and decompress_string) you can safely pass urls now and read them well at the other end.

Example:

print url('bookmark/add/'. compress_string('some/path/on/my/site?query=test'));
function compress_string($string) {
  return urlsafe_base64_encode(gzcompress($string, 9));
}

function decompress_string($string) {
  return gzuncompress(urlsafe_base64_decode($string));
}

function urlsafe_base64_encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function urlsafe_base64_decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}
Written on November 19, 2008 at 18:11, tagged as Drupal, module development, paths

About

drupalcoder.com is a blog on all things Drupal in specific and LAMP on OS X in general. It is maintained by Davy Van Den Bremt, a Belgian (Drupal) web developer and designer living in Ghent. The goal of this blog is to log all interesting things that have crossed the writer's path while developing Drupal sites. You can read all about Davy's professional activities on his LinkedIn profile. If you want to get in touch, use the contact form.