Passing urls as path arguments in urls

Printer-friendly version

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);
}

Comments

Davy Van Den Bremt's picture

Explode

Hi Martijn, no idea what your format is, but in this case explode will be great help to you I guess...

$parts = explode('-', arg(2));
$flight_part = $parts[0];

Instead of / the subargument before a hypen

Hi Davy

I have the following url I want to work with:
www.trekking-world.com/India/Nepal/Flight-schedule
I know I can get the arguments using arg(0) = India, arg(1) = Nepal and arg(2) = Flight-schedule.

Is there also a way to get to the "Flight" string within arg(2) using your method?
Could you give example code how to do this with views argument handling or header code?
Thanks a lot in advance for your answer!
Greetings,
Martijn

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <javascript>, <mysql>, <php>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options