CakePHPでリダイレクトの設定をする

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にリダイレクトされました。
 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930