HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

CodeIgniter AJAX messages submission security issue

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ajaxissuesecuritymessagessubmissioncodeigniter

Problem

I have a small social networking site built in CodeIgniter. Any registered user can send messages to others by visiting their profile.

Today I noticed that one user sent bulk messages to 200 users. How he was able to do that?

Suggestions to make the code secure are welcome.

I have a textarea and a send button on the profile page.

jQuery code on profile page (View)

$("#send").click(function(event){ 
    var msg=$("#quick_message").val();
    var uid=$(this).attr('uid');

    if(msg.length > 0) {
        $("#msg_status").html('');

        $.post("message/send_message", {"ids":uid,"msg":msg}, function(data){

        $("#msg_status").html('Message sent.');
        $("#quick_message").val('');
        });
    } else {

    $("#msg_status").html('Write something to send message.');
    }
});


Here is my controller

// send message
   function send_message()
 {
    if (!$this->users->is_logged_in()) {
    redirect('signin');
    }

    $user_id=$this->session->userdata('user_id');
    $ids=trim($this->input->post('ids'));
    $msg=trim($this->input->post('msg'));
    $msg=htmlspecialchars($msg);
    $msg=$this->replaceTolink($msg);
    $msg=$this->replaceTowinks($msg);

    $pieces=explode(",", $ids);
    foreach ($pieces as &$user_id2) {
    $this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $user_id2,'message' => $msg)); 
    }

    return true;
}


What I need to improve in my code and how to protect the code to send bulk messages?

Solution

First of all you should use site_url() in your jquery code instead of base_url() as it provides url flexibility. For more info visit http://codeigniter.com/user_guide/helpers/url_helper.html

And in your controller code i suggest you to use bulk insert instead of loop insert. So you may use this piece of code:

foreach( $pieces as $user_id2)
{
    $insert_arr[] = array('user_id1'=> $user_id, 'user_id2'=> $user_id2, 'message'=>$msg);
}

$this->db->insert_batch('messages', $insert_arr);

Code Snippets

foreach( $pieces as $user_id2)
{
    $insert_arr[] = array('user_id1'=> $user_id, 'user_id2'=> $user_id2, 'message'=>$msg);
}

$this->db->insert_batch('messages', $insert_arr);

Context

StackExchange Code Review Q#12462, answer score: 3

Revisions (0)

No revisions yet.