Home > OS >  codeigniter 4 url ​goes into loop
codeigniter 4 url ​goes into loop

Time:12-25

I think the problem may be from LanguageControl. Refreshing the page by repeating the url all the time. I am using multi-language support in the admin panel. Below are all the code blocks that I think might be the problem.

route

$routes->get('/', 'Frontend\Home::index', ['as' => 'homepage']);

controller

class Home extends BaseController
{
    public function index()
    {
        return sdc_theme_view('index');
    }
}

sdc_theme_view

function sdc_theme_view($path, $data = [])
{
    $viewPath = THEMES_PATH . sdc_theme_folder();
    $renderer = \Config\Services::themeRenderer($viewPath, null, true);
    $shortcoder = new \Seiler\Shortcoder\Shortcoder();
    $shortcoder->add(shortcodes());
    return $shortcoder->parse($renderer->setData($data)->render($path));
}

LanguageControl

class LanguageControl implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $referer = (string) Services::request()->getServer('HTTP_REFERER');

        $_SESSION['_ci_previous_url'] = $referer;

        $uri = new \CodeIgniter\HTTP\URI(current_url());

        $segments = $uri->getSegments();

        if (!isset($segments[0]) || !in_array($segments[0], config('app')->supportedLocales)){
            array_unshift($segments, config('app')->defaultLocale);
            $query = $uri->getQuery();
            $new_uri = implode('/', $segments);
            $new_uri = $query ? $new_uri . '?'. $query : $new_uri;
            return redirect()->to(base_url($new_uri));
        }
    }

.env

app.baseURL = 'http://localhost/sdcms/'

enter image description here

CodePudding user response:

I'm pretty sure you need to replace the array_unshift. For me, when I set your code up, I needed to look at $segments[1] so forgive me if you need to tweak this slightly:

unset($segments[1]);
$segments[] = $defaultLocale;

My complete code for your example (but using $variables for your supported and default locales):

public function before(RequestInterface $request, $arguments = null){
    $uri = new \CodeIgniter\HTTP\URI(current_url());

    $segments = $uri->getSegments();

    $supportedLocales = array('en','fr');
    $defaultLocale = 'en';

    if (!isset($segments[1]) || !in_array($segments[1],$supportedLocales)){
        unset($segments[1]);
        $segments[] = $defaultLocale;

        $query = $uri->getQuery();
        $new_uri = implode('/', $segments);
        $new_uri = $query ? $new_uri . '?'. $query : $new_uri;

        return redirect()->to(base_url($new_uri));
    }
}

Please let me know if I am missing something.

  • Related