views:

243

answers:

4

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?

A: 

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.

Buggabill
I already have that in my controller file; that doesn't prevent accessing the function via a URL.
rebjr
A: 

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...
}
rebjr
If you make it private like that, how do people purposefully get to it? Not sure it's the best way, but I've been directing people to another page where they confirm that they want to delete the item and then they post to the confirmation method. I check to see if they've posted and process the action if they did.
someoneinomaha
A: 

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.

GSto
A: 

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.

Stephen Curran
Not to mention that CSRF attacks are probably easier if you're using a GET. Someone could post something like <img src='http://www.example.com/item/delete/3' ?> and if the admin user viewed it, the delete function would fire. Granted, the same thing could be done with a post, but it would be more difficult, I would think.
someoneinomaha
Completely agree. Good point.
Stephen Curran