Home     Articles & Projects     Products & Web Services     Forum

Passing variables and .htacces Rewrites

Hi David,

I have set up rewrites successfully with .htaccess but would now like to pass additional variables with the url.

In specific I would like the user to be able to select which currency the parsed results will be shown in. Laterooms offer this by adding

cur=USD

to the end of the xml URL. How is this possible when the urls have been rewritten?
http://www.scottishhotels.net/test/scottish-hotel/()/(101191)Grosvenor-Hotel.html?cur=USD
or
http://www.scottishhotels.net/test/scottish-hotels/(16278654)Auchinleck/?cur=USD

Is there a way to do this and also to make the choice "global" so that all the results remain in USD until it is changed?

Thanks,
Simon

Hi Simon, 2 separate parts

Hi Simon,

2 separate parts to this - getting extra parameters off the URL (that's straight forward - see below), and persisting the choice - the obvious mechanism for which is using a cookie.

Firstly, to access extra query string parameters you simply add:

&%{QUERY_STRING}

...to the end of the rewrite version of the URL. This is assuming that the rewritten version already has query string parameters involved (they almost always do); otherwise you would replace & with a ? in the above text. Here's an example:

RewriteRule ^hotel/(.*).html$ hotel.php?id=$1&%{QUERY_STRING} [L]

To persist a value using cookies, the basic idea is to load a variable with the option; either from the query string (if it exists), or from a cookie (if it exists), or from a default setting (in that order), and then set a cookie with the preference. For example:

<?php
// check for currency value on query string or cookie (in that order)
// or set default value
if ($_GET["cur"])
{
 
$cur = $_GET["cur"];
}
elseif(
$_COOKIE["cur"])
{
 
$cur = $_COOKIE["cur"];
}
else
{
 
$cur = "GBP"; // set the default value here
}
// now set a cookie for next time
setcookie("cur",$cur,strtotime("+1 Year"),"/");
?>

strtotime() is the easiest way to establish an expiry period, and you can use any terminology supported by that function, for example "+1 Day" or an actual date value. If you only want the cookie to last for the current session, use an actual value of zero instead. Note that setcookie() must be called before any output is generated by your script as it sets a HTTP header!

Hope this helps,
Cheers,
David.

Hi David, I hope you are

Hi David,

I hope you are well?

How do you go about setting out the .htaccess fle for a specific url that could have a single or multiple variables.

For example....

category.php?c=$1
would be category/cars/

and

category.php?c=$1&m=$2
would be category/cars/spares/

and

category.php?c=$1&m=$2&p=$3
would be category/cars/spares/tyres/

Just not sure if you would use 1 "RewriteRule ^" or multiple to accommodate the variables...

Thanks in advance for your help.

Simon.
Compare Electricals