Grow your CSS skills. Land your dream job.

PHP Redirect

  • # June 9, 2009 at 2:01 pm

    Hi,
    I would like to make an area in my site that will redirect people depending on where they are. Such as people from the US will get example.com/us/ and people from the uk will just get example.com/uk/.

    I do have a reason for wanting to do this but I have not found out how yet.

    Another thing I was looking for what how to redirect ipods to a mobile site… I found it out in JS so thought I would share it:

    Code:

    I put it in a PHP that will get a variable which will remove it so that people have the option of going back to the normal site if they want.

    Anyway, If you know how to do the country redirect can you post it?
    Regards and thanks

    P.S. Other redirect scripts would be useful just to keep… Like redirecting because of operating system or other things.

    # June 9, 2009 at 6:33 pm

    You can redirect for iPhone based on the user agent string like this :

    Code:
    < ?php
    $user_agent = $_SERVER["HTTP_USER_AGENT"];
    if ( preg_match('/iPhone/i', $user_agent) ) {
    header("Status: 301 Moved Permanently");
    header("Location: URL HERE");
    }
    ?>

    There are several IP geolocation web services available on the net. I found one at ipinfodb.com that has a very simple interface, so here’s the code (it’s very rough and ready but you should be able to expand on it to suit your needs):

    Code:
    < ?php
    if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
    $ip = $_SERVER['REMOTE_ADDR'];
    }

    $url = "http://ipinfodb.com/ip_query_country.php?ip=$ip";

    $xml = simplexml_load_string(geturl($url));

    switch ($xml->CountryCode) {
    case ‘US’:
    redirect(“us”);
    break;
    case ‘GB’:
    redirect(“uk”);
    break;
    default:
    redirect(“other”);
    break;
    }

    function geturl($url) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_HEADER, 0);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($c);

    curl_close($c);

    return $response;
    }

    function redirect($location) {
    header(“Status: 301 Moved Permanently”);
    header(“Location: $location”);
    }
    ?>

    # June 10, 2009 at 5:31 am

    Hi,
    Thanks for your help. I have looked at the code and it all looks good! I don’t quite know why but everyone is passing through as "default" and going to what i have set up that to be. The website does say my location as I went on it before.
    Any ideas why?

    Apart from that this has helped with the iPod thing in PHP and also given me some help with PHP :)

    Regards

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".