設定路由 /application/config/routes.php
$route['api/v1/url/(:any)']['put'] = '/api/v1/url/edit/$1';
寫Controller application/controllers/api/v1/url.php
public function edit($shorten_url) {
if (!$shorten_url || $shorten_url == '') {
http_response_code(400); //HTTP 400 - Bad Request
}
parse_str(file_get_contents('php://input'), $_PUT); //設定$_PUT,因為php預設沒有$_PUT
$database = $this->load->database('default',true); //設定database連線
$query = $database
->from('urls')
->where('url_shorten',$shorten_url)
->get();
if (!$query->num_rows() > 0) { //查詢資料庫是否有這筆紀錄
show_404(); //如果沒有回覆HTTP 404 - Not Found
die(); //結束程式
}
$database
->set("url_dest", $_PATCH['new_url_dest'])
->where('url_shorten',$shorten_url)
->update('urls',$dbdata); //寫入database
if ($$database->error()['code'] != 00000) { //如果發生DB Error
print_r(
json_encode(
array(
'status' => 'error',
'message' => 'an database error occurred',
'code' => $dberror['code'],
)
)
);
http_response_code(500);
die();
}
print_r(
json_encode(
array(
'status' => 'success'
)
)
);
}