/application/config/routes.php
$route['(:any)'] = 'url/redirect/$1'; //要放在最下面!
/application/controllers/url.php
<?php
defined('BASEPATH')or show_403();
class Url extends CI_Controller
{
function redirect($surl) {
$database = $this->load->database('default',true); //連接至default設定檔
$query = $database //SELECT * FROM `urls` WHERE `url_shorten` = "$dest";
->from('urls')
->where('url_shorten',$surl)
->get();
if ($query -> num_rows() > 0) { //撿查url是否存在
$query = $query->result_array(); //取得查詢結果
redirct($query[0]['url_dest']) //執行301 Redirect
} else {
show_404(); //不存在回復404 Not Found
}
}
}
現在應該可以正常運作了!利用昨天的api生成一個短網址來測試看看吧!
有問題歡迎把錯誤訊息丟上來!