Passing current or last page full URL as a part of URL

By using five separate PHP functions, in correct order, you can easily pass (code and decode) entire page’s URL as a parameter of any other script call, redirect etc. And be sure that it will be read (decoded) correctly, no matter, how long your URL is or what kind of characters it is using.

You can encode any URL (current page, last visited page or any otherwise important) and pass it in another URL in the way that your user won’t notice that you’re actually passing an URL.

Presented solution can potentially be used as URL shortening service. Generated URLs aren’t that short (as maybe expected), but for really long URLs it does provides some shortening.

To encode an URL we can use following code:

[code language=”php”]
function encodeUrl($data)
{
return urlencode(base64_encode(addslashes(gzcompress(serialize($data), 9))));
}
[/code]

Even though it is a one-liner to uses five different PHP functions:

To decode URL we can use following code:

[code language=”php”]
function decodeUrl($data)
{
return unserialize(gzuncompress(stripslashes(base64_decode(urldecode($data)))));
}
[/code]

Again, we’re using five different PHP functions:

Here is a simple example on how you can use this solution:

[code language=”php”]
/**
* In encoder / generator.
*/
$url = Yii::app()->request->getUrl();
$cmp = encodeUrl($url);

/**
* In decoder / reader.
*/
echo($url.'<br />’);
echo($cmp.'<br />’);
echo(decodeUrl($cmp).'<br />’);
[/code]

You can encode any kind of URL you’d like. Some examples:

  • last visited page: $url = $_SERVER['HTTP_REFERER'];,
  • full current URL: $url = Yii::app()->request->getUrl();,
  • current route (controller/action) only: Yii::app()->controller->getId().'/'.Yii::app()->controller->getAction()->getId();.

I was inspired by by this comment made to xreturnable Yii extension.

Leave a Reply