我想使用CI为我的项目缩短网址。我可以缩短长网址,但问题是,简而言之,我无法重定向原始网址。
这是我的控制器代码。
<?php
if (!defined('BASEPATH')) {exit ('No direct script access allowed');}
class Shorten extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('shorten_mdl');
}
public function index(){
$this->load->view('home');
}
public function create(){
$short_url = "";
$url = prep_url($this->input->post('url'));
$link_length = $this->config->item('link_length');
$existing_alias = $this->shorten_mdl->alias_from_url($url);
$this->form_validation->set_rules('url','URL','trim|required|xss_clean');
if ($this->form_validation->run()== FALSE) {
$this->index();}
else {
if ($existing_alias == "") {
$alias = random_string('alnum',$link_length);
while($query = $this->shorten_mdl->does_alias_exist($alias)){
$alias = random_string('alnum',$link_length);}
$this->shorten_mdl->save_new_alias($url,$alias);
$short_url = $alias;
}
else {
$short_url = $existing_alias;
}
$this->get_short_url($short_url);
}
public function get_long_url(){
$alias = $this->uri->segment(1);
redirect($this->shorten_mdl->get_long_url($alias));
}
public function error_404(){
echo "Nothing! Fool";
}
}
?>
这是我的型号代码
<?php
if (!defined('BASEPATH')) {echo "No direct script access allowed";}
class shorten_mdl extends CI_Model{
public function __construct(){
parent::__construct();
}
public function save_new_alias($url, $alias){
$data = array('alias'=>$alias,'url'=>$url,'created'=>date('Y-m-d H:i:s'));
$this->db->insert('links',$data);
}
public function alias_from_url($url){
$alias = "";
$this->db->select('alias');
$query = $this->db->get_where('links', array('url'=>$url),1,0);
if ($query->num_rows() > 0) {
foreach ($query->result() as $row){
$alias = $row->alias;
}
}
return $alias;
}
public function does_alias_exist($alias){
$this->db->select('id');
$query = $this->db->get_where('links', array('alias'=>$alias), 1,0);
if ($query->num_rows()>0){
return TRUE;
}
else {
return FALSE;
}
}
public function get_long_url($alias){
$alias="";
$this->db->select('url');
$query = $this->db->get_where('links', array('alias'=>$alias),1,0);
if ($query->num_rows()>0) {
foreach ($query->result() as $row) {
return $row->url;
}
}
return '/error_404';
}
}
?>
这是我的观点。
<h1>Short your url with CI</h1>
<div id="urldiv">
<a href=""><?php echo base_url() . $shorturl;?></a>
</div>
我在路线档案中做了一些更改。
$route['default_controller'] = "shorten";
$route['404_override'] = 'shorten/get_long_url';
$route['error_404'] = 'shorten/error_404';
答案 0 :(得分:1)
雅虎!终于我明白了。模型所需的变更
public function get_long_url($alias){
$this->db->select('url');
$query = $this->db->get_where('links', array('alias'=>$alias),1,0);
if ($query->num_rows()>0) {
foreach ($query->result() as $row) {
return $row->url;
}
}
return '/error_404';
}
控制器需要更改
public function get_long_url($alias=""){
$alias = $this->uri->segment(1);
redirect($this->shorten_mdl->get_long_url($alias));
}