Page 1 of 1
Can I re-write a URL on the fly?
Posted: Mon Jun 17, 2013 11:29 am
by simonmlewis
/index.php?page=search&menu=home&search=xlshirt
Hi
This URL is taken from a variable. But it now needs to be used in a mobile site, and as such, part of the URL needs changing.
So - I need to change "index.php" to "index_ip.php", "page=search" to be "page=isearch" and remove "&menu-home"... if possible.
I really can't see see how to do it. I thought a simple find and replace, but I'm not getting it right.
There must be a simpler way.
Re: Can I re-write a URL on the fly?
Posted: Mon Jun 17, 2013 12:23 pm
by MindOverBody
You can set location via header... (Redirect)
Check this:
http://php.net/manual/en/function.header.php
Re: Can I re-write a URL on the fly?
Posted: Mon Jun 17, 2013 12:50 pm
by simonmlewis
So you cannot simply say: display : /mobile, for /index_ip.php?page=ihome??
Re: Can I re-write a URL on the fly?
Posted: Mon Jun 17, 2013 2:41 pm
by requinix
I would do it like
Code: Select all
// filenames to replace
$filenames = array(
"/index.php" => "/index_ip.php"
);
// query string arguments to replace
$querystrings = array(
"page" => array("search" => "isearch"),
"menu" => array("home" => null) // delete
);
$oldurl = "/index.php?page=search&menu=home&search=xlshirt";
// replace the filename
$file = parse_url($oldurl, PHP_URL_PATH);
if (isset($filenames[$file])) {
$file = $filenames[$file];
}
// replace the query string
parse_str(parse_url($oldurl, PHP_URL_QUERY), $oldqs);
$newqs = array();
foreach ($oldqs as $key => $value) {
if (isset($querystrings[$key]) && array_key_exists($value, $querystrings[$key])) {
$value = $querystrings[$key][$value];
}
if ($value !== null) {
$newqs[$key] = $value;
}
}
$newurl = $file . ($newqs ? "?" . http_build_query($newqs) : "");
rather than with brutish string replacements.
Re: Can I re-write a URL on the fly?
Posted: Tue Jun 18, 2013 3:15 am
by simonmlewis
Genius! Trying to read it to understand how it's working. Thanks a mill.