mattl
mattl

Reputation: 13

PHP: Best redirect technique

I'm currently using the excellent mobile detection script from: detectmobilebrowsers.mobi

This works really well however, it redirects every and any page on your main site (including any query parameters) to your mobile site's home page.

What I need is:

http://www.mydomain.com/page.php?var1=X&var2=Y

to direct to:

http://mobile.mydomain.com/page.php?var1=X&var2=Y

I have multiple pages that should redirect with the query string to their mobile versions.

What's the best way to approach this? I thought that I should:

Examine the $_SERVER['HTTP_REFERER'] for the page and query string, use a switch/case to loop through the 10 or so pages that I need matching on the main and mobile sites then change the referer URL in the mobile detection script.

Does this make sense?

I've been struggling to get the page and query... any advise and thoughts welcome.

Upvotes: 1

Views: 277

Answers (3)

dimme
dimme

Reputation: 4424

In addition to Andy's answer, when redirecting you should set the response status to 301.

Be careful, you may not call header() if you have printed any HTML or echoed anything before calling the function.

if ($mobile_is_detected) {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://mobile.mydomain.com' . $_SERVER['REQUEST_URI']);
}

Upvotes: 2

Andy Baird
Andy Baird

Reputation: 6228

if ($mobile_is_detected) {
    header('Location: http://mobile.mydomain.com' . $_SERVER['REQUEST_URI']);
    exit;
}

Upvotes: 3

middus
middus

Reputation: 9121

You can use $_SERVER['QUERY_STRING'] to redirect to add the query string to the redirect URL in the first place.

Upvotes: 0

Related Questions