CakePHP 中的重定向循环

发布于 2024-11-16 19:40:36 字数 376 浏览 1 评论 0原文

我正在开发 CakePHP 应用程序。我试图根据用户的 IP 地址将用户重定向到管理 URL,为此我在 app_controller.php 中使用此代码,

        if(env('REMOTE_ADDR')=='foo') {

        $this->redirect(array('action'=>'index', 'admin'=>1));
        echo $html->link(__('Logout', true), array('controller'=> 'users', 'action'=>'admin_index')); 
        }

只要条件匹配,我就会得到重定向循环。 :(

I'm working on a CakePHP application. I'm trying to redirect the user to admin URL based on his/her IP address and for that I'm using this code in app_controller.php

        if(env('REMOTE_ADDR')=='foo') {

        $this->redirect(array('action'=>'index', 'admin'=>1));
        echo $html->link(__('Logout', true), array('controller'=> 'users', 'action'=>'admin_index')); 
        }

I'm getting a redirect loop as soon the condition matches. :(

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥枳 2024-11-23 19:40:36

这是因为您的应用程序控制器会先触发代码。您编写的代码本质上会转换为

  1. Visit URL => AppController 触发,将您发送到 /admin/controller/index/
  2. 在 /admin/controller/index/ AppController 再次触发并将您发送到 /admin/controller/index/
  3. 如上

另一件事,您似乎在执行后回显链接重定向,这没有任何目的。

您可能想要的是这样的

$url = 'Wherever you are redirecting to';
if (env('REMOTE_ADDR') == 'foo' && $this->params['url']['url'] != $url) {
   $this->redirect($url);
}

另外,当您执行 $this->redirect(array('action'=>'index', 'admin'=>1)); 时,您本质上是重定向到您所在的 URL 的索引操作。这是您想要做的吗?如果是这样,您需要将支票修改为类似的内容

$url = 'Wherever you are redirecting to';
if (env('REMOTE_ADDR') == 'foo' && $this->params['action'] != 'index' && $this->params['admin'] != 1) {
   $this->redirect($url);
}

This is because your app controller fires code before anything else. The code you've written essentially translates to

  1. Visit URL => AppController fires, sends you to /admin/controller/index/
  2. In /admin/controller/index/ AppController fires again and sends you to /admin/controller/index/
  3. As above

Another thing, you seem to be echoing a link after you do a redirect, this doesn't serve any purpose.

What you probably want is something like this

$url = 'Wherever you are redirecting to';
if (env('REMOTE_ADDR') == 'foo' && $this->params['url']['url'] != $url) {
   $this->redirect($url);
}

Also, when you do $this->redirect(array('action'=>'index', 'admin'=>1)); you're essentially redirecting to the index action of whichever URL you are in. Is this what you're trying to do? If so, you'll need to modify your check to something like

$url = 'Wherever you are redirecting to';
if (env('REMOTE_ADDR') == 'foo' && $this->params['action'] != 'index' && $this->params['admin'] != 1) {
   $this->redirect($url);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文