CakePHPでリダイレクトの設定をしてみます。
サンプルコード
リダイレクトにはredirect()のメソッドを使用します。
src\Controller\RedirectController.php
<?php
namespace App\Controller;
class RedirectController extends AppController
{
public function index()
{
return $this->redirect(
['controller' => 'Test', 'action' => 'index']
);
}
}
http://localhost:8765/testにリダイレクトされました。
引数は相対URLや絶対URLでも指定できます。
src\Controller\RedirectController.php
<?php
namespace App\Controller;
class RedirectController extends AppController
{
public function index()
{
return $this->redirect('/test');
}
}
src\Controller\RedirectController.php
<?php
namespace App\Controller;
class RedirectController extends AppController
{
public function index()
{
return $this->redirect('http://localhost:8765/test');
}
}
http://localhost:8765/testにリダイレクトされました。
actionにデータを渡すこともできます。
src\Controller\RedirectController.php
<?php
namespace App\Controller;
class RedirectController extends AppController
{
public function index()
{
$data = 'noel';
return $this->redirect(
['controller' => 'Test', 'action' => 'index', $data]
);
}
}
http://localhost:8765/test/index/noelにリダイレクトされました。
パラメータやハッシュを設定したい場合、以下のように指定します。
src\Controller\RedirectController.php
<?php
namespace App\Controller;
class RedirectController extends AppController
{
public function index()
{
$data = 'noel';
return $this->redirect(
[
'controller' => 'Test',
'action' => 'index',
'?' => [
'name' => 'noel',
'year' => 7
],
'#' => 'method'
]
);
}
}
http://localhost:8765/test?name=noel&year=7#methodにリダイレクトされました。
【参考サイト】
コメントが承認されるまで時間がかかります。