Moving data in and out of Second Life

My plan for (virtual) world domination is moving fairly slowly, so I thought I might as well just release the voting code here. This is published under GPL3, so do what you want with it... reuse it, re-release it, sell it, whatever... just give me credit as the original author.

The following LindenScript code it adapted from the LSL Script Library. Everything in Second Life has a key which identifies it uniquely; in this case we're interested in the id of the http request itself, which is populated using the function llHTTPRequest. The webserver should respond with a standard http response, which we're capturing with the http_response function. If the returned id matches our known request id, we can be sure that we have the correct response. Then we just "say" the returned value to the avatar using llOwnerSay(). Kewl huh?


key http_request_id;
 
default
{

  touch(integer num_detected)
     {
        http_request_id = llHTTPRequest("http://www.example.com/vote.php?action=new_vote", [], "");
     }
 
  
  http_response(key request_id, integer status, list metadata, string body)
    {
        if (request_id == http_request_id)
        {
            llOwnerSay(body);
        }
    }
}

Ok, so once the user clicks the HUD we now have a http request which goes from Second Life out to your webserver. In this case the request is to a file named vote.php

The following PHP code is an example skeleton implementation. You'll see that SL sends it's own headers with the request. This allows us to grab all kinds of information about the avatar or script that made the request.

Notice that to send data back into Second Life, we just echo out as if writing to a web page. Anything which is in the response body will be picked up by our LSL script.


query($query_check);
	if($Db->affected_rows() > 0)
	{
		echo "You have already voted for this region.";
	}
	else {
		$query_vote = "INSERT INTO `votes` (etc, etc, etc);";
		$Db->query($query_vote);
		if($Db->affected_rows() > 0)
		{
			echo "Thanks for voting.";
		}
	}
}
else {
	echo "You can only access this page from within Second Life.";
}
?>