Welcome Guest, Not a member yet? Register   Sign In
url helper extension [safe_url]
#1

[eluser]Hannes Nevalainen[/eluser]
I developed som tiny helper functions for the url helper.

If you have links on your site like this http://mydomain.com/blog/delete/23 it's easy for the an user to change that id to something else and delete something that should not be deleted.

With safe url a hash is added as the last segment in the url http://mydomain.com/blog/delete/23/6ca40...f215a7d7b1.
If a user changes the uri in someway the hash would not be the same and the function validate_safe_url() would return false;

Extension to the url helper
Code:
#Returns the safe url for the provided URI
function safe_url($uri){
    return site_url(trim($uri,'/').'/'.safe_url_hash($uri));
}

#Creates a "safe" link
function safe_anchor($uri,$title = null, $attr = null){    
    return anchor(safe_url($uri), $title, $attr);
}

#Hash provided uri
function safe_url_hash($uri){
    return md5(trim($uri,'/').config_item('encryption_key'));
}

#Validates Current URL
function validate_safe_url(){
    $segments =& get_instance()->uri->segments;
    $uri = implode('/', array_slice($segments,0,-1));
    return safe_url_hash($uri) === $segments[count($segments)];
}
Sample Code
Code:
class Blog extends Controller{

  public function Blog{
    parent::Controller();
    $this->load->helper('url');
  }

  public function index(){
    echo safe_anchor('blog/delete/23');
  }

  public function delete($id){
    if(validate_safe_url()){
      $this->load->model('Blog_model');
      $this->Blog_model->delete($id);
    }
    redirect('blog');
  }

}

Notify, you should set your encryption_key in config.php for this to be "safe"/safer.




Theme © iAndrew 2016 - Forum software by © MyBB