嗨,我需要重定向到别名在url与codeigniter…例如如果用户在浏览器中输入http://www.website.com/fedex,需要获得类似fedex的别名,并通过此别名在数据库中查找,并重定向到正确的url,必须是http://www.website.com/pages/fedex…这是我的代码…
PD: By way不存在名为fedex的控制器。
. .routes.php…
$route['default_controller'] = "alias";
$route['404_override'] = '';
$route[':any'] = "alias/index/$1";
. .
class Alias extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$alias = $this->uri->segment(1);
echo "Alias:" . $alias;
}
}
我认为这就是你想要做的…
class Alias extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function index(){
echo 'Default page!';
}
public function get($alias)
{
$this->db->from('users')->where(array('username' => $alias));
$query = $this->db->get();
if ($query->num_rows() > 0){
//This means that a row was returned from the database and their is a user that exists with that name
redirect("/pages/$alias");
}
else{
echo 'There is no user that exists with that username';
}
}
public function pages($alias){
echo "Hey $alias!";
}
}
//Routes
$route['default_controller'] = "alias";
$route['404_override'] = '';
$route['pages/:any'] = "alias/pages/$1";
$route[':any'] = "alias/get/$1";
在构造函数中,它加载数据库类和URL帮助器。在index()方法中,它使用数据库从"users"表中选择用户名为$alias的一行。然后用if语句检查是否从数据库返回了一行。如果返回一行,则意味着用户退出并重定向到/pages/username。否则它会回显说没有人使用该用户名退出。
确保更改数据库信息匹配您的数据库设置以及确保$active_record在数据库配置文件中设置为TRUE