I have 开发者_运维知识库a simple controller function which deletes a DB entry (it uses a model function to do so). I have a link to this in one of my views (e.g. http://www.example.com/item/delete/3) and I’m using jQuery to display a confirm dialog to make sure the user really wants to delete it. All fine. However if you just enter that URL in your browser the item is deleted without warning.
Is there a way to handle this either in the way I code the controller function or in the model?
For a delete operation I would do a HTTP post.
function delete()
{
if ($id = $this->input->post('id'))
{
$this->item_model->delete_item($id);
}
}
And then my JQuery would do a HTTP post.
$.ajax({
type: 'POST',
url: 'item/delete',
data: {id:item_id}
});
This way a client won't be able to accidentally delete an item through browsing to the URL in their web browser.
You can prevent this by adding this line to the top of the model and controller files (CI Forum post).
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class SomeModel extends Model
{
// model code
}
?>
This insures that CI has been loaded.
I think I figured it out, and that is to make the function private in the controller, i.e.
function _delete($id) {
...delete code goes here...
}
Is this through an AJAX request? If so, I would send the data to delete via POST instead of GET, so that it can't be navigated to directly.
If it's through GET, I imagine that the confirm warning is being thrown on the link click, I would instead have it load when you go to the page directly.
You could also check the referrer, and only have it work it the referring page is valid, but this method isn't always 100% reliable.
精彩评论