最近,我将WIP站点从带有WAMP的Windows XP机器移到了带有MAMP的MacBook。当我测试网站时,我发现重定向(即$this->redirect="Index.php";
)似乎不起作用。它们在Windows XP机器上运行良好。
我使用前控制器模式。索引页面如下所示:
Index.hp:
<?php
.....
switch ($action){
case 'logoff':
require_once('Controller_Logoff.php');
$command=new controller_Logoff();
break;
case 'register':
require_once('Controller_Register.php');
$command=new controller_Register();
break;
...
}
...
$command->execute($view);
$menu=array(
new MenuEntry("Logoff","Index.php",array("action"=>"logoff")),
new MenuEntry("Register","Index.php", array("action"=>"register")),
....
) // This menu is shown on the user's view
if ($command->getRedirect()){ //This case doesn't work
header('Location:'.$command->getRedirect());
}else if ($command->getInclusion()){ //This case works
include ("UI_Header.php");
include ("UI_Menu.php");
include ("UI_Message.php");
echo "<div class='content'>";
include ($command->getInclusion());
echo "</div>";
include ("UI_Footer.php");
}
问题似乎发生在这个阶段:header('Location:'.$command->getRedirect());
注意,如果我执行header('Location: http://localhost:8888/'.$command->getRedirect());
,它仍然会失败。
我还试图在我的脚本中包含ob_start();
,但没有效果。
一个控制器页面上的例子(在新用户注册结束时)我有:
Controller_register.php:
<?php
class Controller_Register extends Controller {
protected $inclusion='UI_Register.php';
function execute($view){
.... // Code to register a new user - that works, i.e., a new user appears in the DB
var_dump("Before redirect");
$this->redirect="Index.php";
var_dump("after redirect");
}
redirect
是用于各种控制器的类中的一个变量。它在父类中被设置为null
。我已经验证了在应该执行标头时,它已更改为正确的值(Index.php
)。
当我运行此代码时,我会得到一个空白页。事件的确切过程是:
- 打开网站-URL为
http://localhost:8888/Project/
- 单击菜单项
register
,它会将我发送到注册页面,该URL为http://localhost:8888/Project/Index.php?action=register
- 在注册表中输入所需信息(用户名、密码和电子邮件),然后单击
submit
-信息已成功加载到数据库中 - 显示了一个空白页面-URL没有更改,仍然是
http://localhost:8888/Project/Index.php?action=register
,但显然没有加载文件(注册页面)
当我开始点击register
链接时,错误日志会产生以下结果:
- 〔09-Oct-2014 23:10:00欧洲/柏林〕PHP警告:无法修改标题信息-标题已由第2行/Applications/MAMP/htdocs/Project/Index.PHP中的/Applications/MP/htddocs/Project/UI_header.PHP发送
- 〔2014年10月9日23:10:07欧洲/柏林〕PHP警告:session_start():无法发送会话缓存限制器-第13行/Applications/MAMP/htdocs/Project/Index.PHP中的标头已发送(输出开始于/Applications/MAFP/htdocs/Project/Index.PHP:1)
output started at /Applications/MAMP/htdocs/Project/Index.php:1)
从Index.php或<?php
前面的任何空格中删除BOM标记
http://en.wikipedia.org/wiki/Byte_order_mark
请阅读这篇文章——https://stackoverflow.com/a/8028987/1164491
我假设您共享的代码只显示您估计相关的部分;基于此,我要做的一件事是在发送header
之后添加exit
,这样你就可以确保在之后不会执行任何代码
...
if ($command->getRedirect()) { //This case doesn't work
header('Location:'.$command->getRedirect());
exit;
} else if ...
var_dump("Before redirect");
$this->redirect="Index.php";
var_dump("after redirect");
这就是导致重定向失败的原因。var转储输出到浏览器,防止重定向发生。试着评论vardumps,看看这是否能奏效。
我还尝试包含ob_start();在我的剧本中,没有效果。
这也应该起作用,但请确保在运行上述代码之前包含这一点。