Can I re-write a URL on the fly?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Can I re-write a URL on the fly?

Post 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.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
MindOverBody
Forum Commoner
Posts: 96
Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia

Re: Can I re-write a URL on the fly?

Post by MindOverBody »

You can set location via header... (Redirect)
Check this: http://php.net/manual/en/function.header.php
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Can I re-write a URL on the fly?

Post by simonmlewis »

So you cannot simply say: display : /mobile, for /index_ip.php?page=ihome??
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can I re-write a URL on the fly?

Post 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.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Can I re-write a URL on the fly?

Post by simonmlewis »

Genius! Trying to read it to understand how it's working. Thanks a mill.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply