Don't click here unless you want to be banned.

LSL Wiki : ExamplellHTTPRequest

HomePage :: PageIndex :: RecentChanges :: RecentlyCommented :: UserSettings :: You are crawl423.us.archive.org
This is a minimalistic approach to setting up a simple request to a remote web server, and get the result.

Limitations: apparently PHP must be compiled as an Apache module (and not using FastCGI) for you to get access to apache_response_headers().
Note: There is an PHP based emulation to the apache_response_headers() while using FastCGI emu_getallheaders()

key requestid; // just to check if we're getting the result we've asked for; all scripts in the same object get the same replies

default
{
    touch_start(integer number)
    {
        requestid = llHTTPRequest("http://my.server.com/my-script.php", 
            [HTTP_METHOD, "POST",
             HTTP_MIMETYPE, "application/x-www-form-urlencoded"],
            "parameter1=hello&parameter2=world");
    }

    http_response(key request_id, integer status, list metadata, string body)
    {
        if (request_id == requestid)
            llWhisper(0, "Web server said: " + body);
    }
}

And here goes myscript.php:

<?
// Only works with PHP compiled as an Apache module
$headers apache_request_headers();

$objectName $headers["X-SecondLife-Object-Name"];
$objectKey     $headers["X-SecondLife-Object-Key"];
$ownerKey     $headers["X-SecondLife-Owner-Key"];
$ownerName $headers["X-SecondLife-Owner-Name"];
$region        $headers["X-SecondLife-Region"];
// and so on for getting all the other variables ...

// get things from $_POST[]
// Naturally enough, if this is empty, you won't get anything
$parameter1    $_POST["parameter1"];
$parameter2    $_POST["parameter2"];

echo 
$ownerName " just said " $parameter1 " " $parameter2 "\n";
?>

Note: if for some reason $_POST[] doesn't return anything, you have to check for other alternatives, like the one described on the first comment on the page for llHTTPRequest (directly reading from the HTTP stream), as per VeloxSeverine's suggestion.

Suggestion: Use $_REQUEST[] instead of $_POST[] as it will work for all types, as well as, POST. SiRiSAsturias

Note: For greater server compatibility and efficiency, use $_SERVER[] instead of apache_request_headers() to access the SL header data. For Example, $_SERVER['HTTP_X_SECONDLIFE_OWNER_NAME']; (notice the format change of the data labels) ~PlexLum

Example: Here is the use of a emulated apache_request_headers() that I wrote; if you're using FastCGI and are used to using the apache function, use this! I hope this helps someone! (It'll also allow you to get the headers if you're not using FastCGI). FoxDiller
Small edit to correct the casing of X-SecondLife headers, as variable names and array keys in PHP are case sensitive. (And in case anyone is wondering, this function also works with PHPSuExec too) - EddyOfarrel
<?php
function emu_getallheaders()
{
    foreach(
$_SERVER as $name => $value)
    if(
substr($name05) == 'HTTP_')
        
$headers[str_replace('X-Secondlife-''X-SecondLife-'str_replace(' ''-'ucwords(strtolower(str_replace('_'' 'substr($name5))))))] = $value;
    return 
$headers;
}

$headers emu_getallheaders(); // Just replace any use of `apache_request_headers()` with `emu_getallheaders()`.

$objectName $headers["X-SecondLife-Object-Name"];
$objectKey $headers["X-SecondLife-Object-Key"];
// ..........................[~ETC ETC~]..........................//
?>

I have been asked to offer my source code for checking HTTP headers, so I present yet another example... the server and client code to check headers... - Ice
<?php
//This simply echoes the headers exactly as it gets them...
//This script requires PHP as an apache module to work

$headers=apache_request_headers();
foreach(
$headers as $key => $val)
{
     echo 
$key.": ".$val."\n";
}
?>
//Ice Brodie's http text output script
//This script requests from our data source (URL) and echoes out what it sends to the owner of the script
//I use this to test my PHP apps personally, it's a simple debugging application so I release it publicly
//You may use, redistribute, modify, copy however you feel would be useful

string URL="http://www.secondlife.com/httprequest/homepage.php";
//Replace URL with the path to your web server.
key http;//This stores the HTTP request we send.

default
{
    touch_start(integer foo)
    {
        http=llHTTPRequest(URL, [] ,"");
    }

    http_response(key id,integer status, list meta, string body)
    {
        if(http==id)
        {
            integer i;
            list lbody=llParseString2List(body,["\r\n","\n"],[]);
            integer count=llGetListLength(lbody);
            //This turns newline characters char(10) into new lines in chat
            // Fixed Dec 8, 2008: Now parses both Unix and Windows style end of lines
            //    Though RFC requires Unix style, this becomes more tolerant.
            for(i=0;i<count;i++)
            {
                llOwnerSay(llList2String(lbody,i));
            }
        }
    }
}
--
Examples
Comments [Hide comments/form]
This is a HTTPRequest to mySQL link script
I paid to have it written for me, but i've never been able to make it work
Maybe someone else can get some good out of it, thanks

<?php

/
* Date: Aug 24th, 2006
* Written for: (Lasivian)
* Description: A simple HTTP request storage bin for external Second Life storage.
/

/
MySQL 4.0 Database Schema

CREATE TABLE `lslstore` (
`data_key` varchar(64) NOT NULL,
`data_group` varchar(64) default NULL,
`data_value` varchar(255) NOT NULL,
Apparently I can;t use 512 on my server,
`agent_id` varchar(36) NOT NULL,
`access_time` timestamp NOT NULL,
UNIQUE KEY `dedupe` (`data_key`,`agent_id`),
KEY `group_agent` (`data_group`,`agent_id`),
KEY `key_agent` (`data_key`,`agent_id`)
) TYPE=MyISAM;

/


/
* Example Usage:
* Store 1: http:localhost/ls.php?command=store&key=name&value=Josh&group=profile&owner_key=1
* Store 2: http:
localhost/ls.php?command=store&key=nick&value=Skiz&group=profile&owner_key=1
* Get: http:localhost/ls.php?command=get&key=name&owner_key=1
* Get Group: http:
localhost/ls.php?command=getgroup&group=profile&owner_key=1
* Delete: http:localhost/ls.php?command=delete&key=name&owner_key=1
* Delete Group: http:
localhost/ls.php?command=deletegroup&group=profile&owner_key=1
/

Database Settings
define('DB_HOST','localhost');
MySQL Server Host
define('DB_USER','USERNAME'); MySQL User
define('DB_PASS','PASSWORD');
MySQL Password
define('DB_NAME','DB_NAME'); The name of the database

Connect to the database or throw a nasty error
$db = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME,$db) or die(mysql_error());

/
* Here is the guts of the script. We are going to validate the request
* that was made to see if it was a valid action then call a function
* that will insert or return the data to the user.
*
* If you only want to allow GET or POST methods you can change the
* parameter that is being passed to the command. REQUEST covers
* nearly all request types including get, post, cookies and sessions.
*
* ex: change cmd_store($_REQUEST) to cmd_store($_POST)
/

switch(strtoupper($_REQUEST['command'])){
case 'STORE':
cmd_store($_REQUEST);
break;
case 'GET':
cmd_get($_REQUEST);
break;
case 'GETGROUP':
cmd_get_group($_REQUEST);
break;
case 'DELETE':
cmd_delete($_REQUEST);
break;
case 'DELETEGROUP':
cmd_delete_group($_REQUEST);
break;
case 'DELETEALL':
cmd_delete_all($_REQUEST);
break;
default:
echo ("Invalid Command Requested");
}

close the database connection
mysql_close($db);

stop execution
die();

//

/

* Database Functionality
* The following functions are passed the full request above and will use that
* request to manage the database and process requests.
/

/
/

/
* Command: STORE
* Usage: Stores a string in the database
* Required Parameters: key, value, group, agent
/
function cmd_store($params){
Check for required parameters
$req = array('key','value','group');
foreach($req as $rkey){
$$rkey = mysql_real_escape_string($params[$rkey]);
}
$owner_id = get_owner_id();
create and execute the query
$sql = "REPLACE INTO lslstore (data_key,data_value,data_group,agent_id, access_time) VALUES ('$key', '$value', '$group', '$owner_id',
NOW())";
$result = mysql_query($sql) or die(mysql_error());
echo 'Store successful.';
}

/
* Command: GET
* Usage: Retrieves a string from the database
* Required Parameters: key
/
function cmd_get($params){
Check for required parameters
$req = array('key');
foreach($req as $rkey){
$$rkey = mysql_real_escape_string($params[$rkey]);
}
$owner_id = get_owner_id();
create and execute the query
$sql = "SELECT data_value FROM lslstore WHERE data_key = '$key' AND agent_id = '$owner_id'";
$result = mysql_query($sql) or die(mysql_error());
spit out the results
while($row = mysql_fetch_assoc($result)){
echo $row['data_value']."\n";
}
}

/
* Command: GET_GROUP
* Usage: Retrieves a set of keys and values for a group
* Required Parameters: key, group
/
function cmd_get_group($params){
Check for required parameters
$req = array('group');
foreach($req as $rkey){
$$rkey = mysql_real_escape_string($params[$rkey]);
}
$owner_id = get_owner_id();
create and execute the query
$sql = "SELECT data_key, data_value FROM lslstore WHERE data_group = '$group' AND agent_id = '$owner_id'";
$result = mysql_query($sql) or die(mysql_error());
spit out the results in format: key=value
while($row = mysql_fetch_assoc($result)){
echo $row['data_key'].'='.$row['data_value']."\n";
}
}

/
* Command: DELETE
* Usage: Deletes a key from the database
* Required Parameters: key
/
function cmd_delete($params){
Check for required parameters
$req = array('key');
foreach($req as $rkey){
$$rkey = mysql_real_escape_string($params[$rkey]);
}
$owner_id = get_owner_id();
create and execute the query
$sql = "DELETE FROM lslstore WHERE data_key = '$key' AND agent_id = '$owner_id'";
$result = mysql_query($sql) or die(mysql_error());
echo 'Deleted...';
}

/
* Command: DELETE_GROUP
* Usage: Deletes a group from the database
* Required Parameters: group
/
function cmd_delete_group($params){
Check for required parameters
$req = array('group');
foreach($req as $rkey){
$$rkey = mysql_real_escape_string($params[$rkey]);
}
$owner_id = get_owner_id();
create and execute the query
$sql = "DELETE FROM lslstore WHERE data_group = '$group' AND agent_id = '$owner_id'";
$result = mysql_query($sql) or die(mysql_error());
echo 'Deleted...';
}

/
* Command: DELETE_ALL
* Usage: Deletes all entries for a agent/owner
* Required Parameters: (none)
/
function cmd_delete_all($params){
$owner_id = get_owner_id();
create and execute the query
$sql = "DELETE FROM lslstore WHERE agent_id = '$owner_id'";
$result = mysql_query($sql) or die(mysql_error());
echo 'Deleted...';
Tell the world we're deleting data
}

returns which owner id to use (modify as needed, uses ENV then owner_key if not set)
function get_owner_id(){
if(isset($_SERVER["HTTP_X_SECONDLIFE_OWNER_KEY"])){
return mysql_real_escape_string($_SERVER["HTTP_X_SECONDLIFE_OWNER_KEY"]);
}else{
if(isset($_REQUEST['owner_key'])){
return mysql_real_escape_string($_REQUEST['owner_key']);
}else{
die('You must specify an owner_key parameter');
}
}
}
?>
-- LasivianLeandros (2006-08-25 23:06:48)
escaping italics, please use put %% aroung your code before posting in the future.
-- BlindWanderer (2006-08-26 20:12:38)
Ah, not with that particular script, since it is a PHP script and not ASP!
-- GwynethLlewelyn (2007-08-05 06:36:30)
Attach a comment to this page: