phpstr-replacerequest-uri

Insert value to URL path


I have a site with content that is different for market locations, so I am setting a cookie for the users location. If a user tries going to a landing page directly I would like to insert the market location to the URL.

For example, if a user tries going to www.mysite.com/packages I would like to update the URL to be www.mysite.com/tampa/packages

I have a cookie set called "market", and this is the code I am trying, but it isn't working.

<?php
switch ($_COOKIE['market']) {

  case "tampa":
    $url = $_SERVER['REQUEST_URI'];
    switch (true) { 
      case strstr($url, 'packages'):
        $currenturl = str_replace('/packages','/tampa/packages/',$url);
        return $currenturl;
        break;
    }
    break;

  // etc for other markets
}

Is PHP the right approach for this? Is there a better solution that would work? Thank you in advance for any help.


Solution

  • You need to use header() function to reload the webpage with the new URL like so:

    Instead of:

    return $currenturl;
    

    Do:

    Header('Location: '.$currenturl);
    

    Be sure there's no output to the browser before doing so though.