OBJECTS
The beauty of the ASP Object Model is that it takes the
burden of CGI and Session Management off the developer,
and puts them in objects accessible from any
ASP script & include. For the perl programmer, treat these objects
as globals accessible from anywhere in your ASP application.
The Apache::ASP object model supports the following:
Object Function
------ --------
$Session - user session state
$Response - output to browser
$Request - input from browser
$Application - application state
$Server - general methods
These objects, and their methods are further defined in the
following sections.
If you would like to define your own global objects for use
in your scripts and includes, you can initialize them in
the global.asa Script_OnStart like:
use vars qw( $Form $Site ); # declare globals
sub Script_OnStart {
$Site = My::Site->new; # init $Site object
$Form = $Request->Form; # alias form data
$Server->RegisterCleanup(sub { # garbage collection
$Site->DESTROY;
$Site = $Form = undef;
});
}
In this way you can create site wide application objects
and simple aliases for common functions.
$Session Object
|
$Response->Write($data)
|
$Session->{CodePage}
|
|
$Session->{LCID}
|
$Request Object
|
$Session->{SessionID}
|
$Request->{Method}
|
$Session->{Timeout} [= $minutes]
|
$Request->{TotalBytes}
|
$Session->Abandon()
|
$Request->BinaryRead([$length])
|
$Session->Lock()
|
$Request->ClientCertificate()
|
$Session->UnLock()
|
$Request->Cookies($name [,$key])
|
|
$Request->FileUpload($form_field, $key)
|
$Response Object
|
$Request->Form($name)
|
$Response->{BinaryRef}
|
$Request->Params($name)
|
$Response->{Buffer}
|
$Request->QueryString($name)
|
$Response->{CacheControl}
|
$Request->ServerVariables($name)
|
$Response->{Charset}
|
|
$Response->{Clean} = 0-9;
|
$Application Object
|
$Response->{ContentType} = "text/html"
|
$Application->Lock()
|
$Response->{Debug} = 1|0
|
$Application->UnLock()
|
$Response->{Expires} = $time
|
$Application->GetSession($sess_id)
|
$Response->{ExpiresAbsolute} = $date
|
$Application->SessionCount()
|
$Response->{FormFill} = 0|1
|
|
$Response->{IsClientConnected}
|
$Server Object
|
$Response->{PICS}
|
$Server->{ScriptTimeout} = $seconds
|
$Response->{Status} = $status
|
$Server->Config($setting)
|
$Response->AddHeader($name, $value)
|
$Server->CreateObject($program_id)
|
$Response->AppendToLog($message)
|
$Server->Execute($file, @args)
|
$Response->BinaryWrite($data)
|
$Server->File()
|
$Response->Clear()
|
$Server->GetLastError()
|
$Response->Cookies($name, [$key,] $value)
|
$Server->HTMLEncode( $string || \$string )
|
$Response->Debug(@args)
|
$Server->MapInclude($include)
|
$Response->End()
|
$Server->MapPath($url);
|
$Response->ErrorDocument($code, $uri)
|
$Server->Mail(\%mail, %smtp_args);
|
$Response->Flush()
|
$Server->RegisterCleanup($sub)
|
$Response->Include($filename, @args)
|
$Server->Transfer($file, @args)
|
$Response->Include(\%cache_args, @sub_args) *CACHE API*
|
$Server->URLEncode($string)
|
$Response->Include(\$script_text, @args)
|
$Server->URL($url, \%params)
|
$Response->IsClientConnected()
|
$Server->XSLT(\$xsl_data, \$xml_data)
|
$Response->Redirect($url)
|
|
$Response->TrapInclude($file, @args)
|
|
|
$Session Object
The $Session object keeps track of user and web client state, in
a persistent manner, making it relatively easy to develop web
applications. The $Session state is stored across HTTP connections,
in database files in the Global or StateDir directories, and will
persist across web server restarts.
The user session is referenced by a 128 bit / 32 byte MD5 hex hashed cookie,
and can be considered secure from session id guessing, or session hijacking.
When a hacker fails to guess a session, the system times out for a
second, and with 2**128 (3.4e38) keys to guess, a hacker will not be
guessing an id any time soon.
If an incoming cookie matches a timed out or non-existent session,
a new session is created with the incoming id. If the id matches a
currently active session, the session is tied to it and returned.
This is also similar to the Microsoft ASP implementation.
The $Session reference is a hash ref, and can be used as such to
store data as in:
$Session->{count}++; # increment count by one
%{$Session} = (); # clear $Session data
The $Session object state is implemented through MLDBM,
and a user should be aware of the limitations of MLDBM.
Basically, you can read complex structures, but not write
them, directly:
$data = $Session->{complex}{data}; # Read ok.
$Session->{complex}{data} = $data; # Write NOT ok.
$Session->{complex} = {data => $data}; # Write ok, all at once.
Please see MLDBM for more information on this topic.
$Session can also be used for the following methods and properties:
$Session->{CodePage}
Not implemented. May never be until someone needs it.
$Session->{LCID}
Not implemented. May never be until someone needs it.
$Session->{SessionID}
SessionID property, returns the id for the current session,
which is exchanged between the client and the server as a cookie.
$Session->{Timeout} [= $minutes]
Timeout property, if minutes is being assigned, sets this
default timeout for the user session, else returns
the current session timeout.
If a user session is inactive for the full
timeout, the session is destroyed by the system.
No one can access the session after it times out, and the system
garbage collects it eventually.
$Session->Abandon()
The abandon method times out the session immediately. All Session
data is cleared in the process, just as when any session times out.
$Session->Lock()
API extension. If you are about to use $Session for many consecutive
reads or writes, you can improve performance by explicitly locking
$Session, and then unlocking, like:
$Session->Lock();
$Session->{count}++;
$Session->{count}++;
$Session->{count}++;
$Session->UnLock();
This sequence causes $Session to be locked and unlocked only
1 time, instead of the 6 times that it would be locked otherwise,
2 for each increment with one to read and one to write.
Because of flushing issues with SDBM_File and DB_File databases,
each lock actually ties fresh to the database, so the performance
savings here can be considerable.
Note that if you have SessionSerialize set, $Session is
already locked for each script invocation automatically, as if
you had called $Session->Lock() in Script_OnStart. Thus you
do not need to worry about $Session locking for performance.
Please read the section on SessionSerialize for more info.
$Session->UnLock()
API Extension. Unlocks the $Session explicitly. If you do not call this,
$Session will be unlocked automatically at the end of the
script.
$Response Object
This object manages the output from the ASP Application and the
client web browser. It does not store state information like the
$Session object but does have a wide array of methods to call.
$Response->{BinaryRef}
API extension. This is a perl reference to the buffered output of
the $Response object, and can be used in the Script_OnFlush
global.asa event to modify the buffered output at runtime
to apply global changes to scripts output without having to
modify all the scripts. These changes take place before
content is flushed to the client web browser.
sub Script_OnFlush {
my $ref = $Response->{BinaryRef};
$$ref =~ s/\s+/ /sg; # to strip extra white space
}
Check out the ./site/eg/global.asa for an example of its use.
$Response->{Buffer}
Default 1, when TRUE sends output from script to client only at
the end of processing the script. When 0, response is not buffered,
and client is sent output as output is generated by the script.
$Response->{CacheControl}
Default "private", when set to public allows proxy servers to
cache the content. This setting controls the value set
in the HTTP header Cache-Control
$Response->{Charset}
This member when set appends itself to the value of the Content-Type
HTTP header. If $Response->{Charset} = 'ISO-LATIN-1' is set, the
corresponding header would look like:
Content-Type: text/html; charset=ISO-LATIN-1
$Response->{Clean} = 0-9;
API extension. Set the Clean level, default 0, on a per script basis.
Clean of 1-9 compresses text/html output. Please see
the Clean config option for more information. This setting may
also be useful even if using compression to obfuscate HTML.
$Response->{ContentType} = "text/html"
Sets the MIME type for the current response being sent to the client.
Sent as an HTTP header.
$Response->{Debug} = 1|0
API extension. Default set to value of Debug config. May be
used to temporarily activate or inactivate $Response->Debug()
behavior. Something like:
{
local $Response->{Debug} = 1;
$Response->Debug($values);
}
maybe be used to always log something. The Debug()
method can be better than AppendToLog() because it will
log data in data structures one level deep, whereas
AppendToLog prints just raw string/scalar values.
$Response->{Expires} = $time
Sends a response header to the client indicating the $time
in SECONDS in which the document should expire. A time of 0 means
immediate expiration. The header generated is a standard
HTTP date like: "Wed, 09 Feb 1994 22:23:32 GMT".
$Response->{ExpiresAbsolute} = $date
Sends a response header to the client with $date being an absolute
time to expire. Formats accepted are all those accepted by
HTTP::Date::str2time(), e.g.
"Wed, 09 Feb 1994 22:23:32 GMT" -- HTTP format
"Tuesday, 08-Feb-94 14:15:29 GMT" -- old rfc850 HTTP format
"08-Feb-94" -- old rfc850 HTTP format
"09 Feb 1994" -- proposed new HTTP format
"Feb 3 1994" -- Unix 'ls -l' format
"Feb 3 17:03" -- Unix 'ls -l' format
$Response->{FormFill} = 0|1
If true, HTML forms generated by the script output will
be auto filled with data from $Request->Form. This feature
requires HTML::FillInForm to be installed. Please see
the FormFill CONFIG for more information.
This setting overrides the FormFill config at runtime
for the script execution only.
$Response->{IsClientConnected}
1 if web client is connected, 0 if not. This value
starts set to 1, and will be updated whenever a
$Response->Flush() is called. If BufferingOn is
set, by default $Response->Flush() will only be
called at the end of the HTML output.
As of version 2.23 this value is updated correctly
before global.asa Script_OnStart is called, so
global script termination may be correctly handled
during that event, which one might want to do
with excessive user STOP/RELOADS when the web
server is very busy.
An API extension $Response->IsClientConnected
may be called for refreshed connection status
without calling first a $Response->Flush
$Response->{PICS}
If this property has been set, a PICS-Label HTTP header will be
sent with its value. For those that do not know, PICS is a header
that is useful in rating the internet. It stands for
Platform for Internet Content Selection, and you can find more
info about it at: http://www.w3.org
$Response->{Status} = $status
Sets the status code returned by the server. Can be used to
set messages like 500, internal server error
$Response->AddHeader($name, $value)
Adds a custom header to a web page. Headers are sent only before any
text from the main page is sent, so if you want to set a header
after some text on a page, you must turn BufferingOn.
$Response->AppendToLog($message)
Adds $message to the server log. Useful for debugging.
$Response->BinaryWrite($data)
Writes binary data to the client. The only
difference from $Response->Write() is that $Response->Flush()
is called internally first, so the data cannot be parsed
as an html header. Flushing flushes the header if has not
already been written.
If you have set the $Response->{ContentType}
to something other than text/html, cgi header parsing (see CGI
notes), will be automatically be turned off, so you will not
necessarily need to use BinaryWrite for writing binary data.
For an example of BinaryWrite, see the binary_write.htm example
in ./site/eg/binary_write.htm
Please note that if you are on Win32, you will need to
call binmode on a file handle before reading, if
its data is binary.
$Response->Clear()
Erases buffered ASP output.
$Response->Cookies($name, [$key,] $value)
Sets the key or attribute of cookie with name $name to the value $value.
If $key is not defined, the Value of the cookie is set.
ASP CookiePath is assumed to be / in these examples.
$Response->Cookies('name', 'value');
--> Set-Cookie: name=value; path=/
$Response->Cookies("Test", "data1", "test value");
$Response->Cookies("Test", "data2", "more test");
$Response->Cookies(
"Test", "Expires",
&HTTP::Date::time2str(time+86400)
);
$Response->Cookies("Test", "Secure", 1);
$Response->Cookies("Test", "Path", "/");
$Response->Cookies("Test", "Domain", "host.com");
--> Set-Cookie:Test=data1=test%20value&data2=more%20test; \
expires=Fri, 23 Apr 1999 07:19:52 GMT; \
path=/; domain=host.com; secure
The latter use of $key in the cookies not only sets cookie attributes
such as Expires, but also treats the cookie as a hash of key value pairs
which can later be accesses by
$Request->Cookies('Test', 'data1');
$Request->Cookies('Test', 'data2');
Because this is perl, you can (NOT PORTABLE) reference the cookies
directly through hash notation. The same 5 commands above could be compressed to:
$Response->{Cookies}{Test} =
{
Secure => 1,
Value =>
{
data1 => 'test value',
data2 => 'more test'
},
Expires => 86400, # not portable, see above
Domain => 'host.com',
Path => '/'
};
and the first command would be:
# you don't need to use hash notation when you are only setting
# a simple value
$Response->{Cookies}{'Test Name'} = 'Test Value';
I prefer the hash notation for cookies, as this looks nice, and is
quite perlish. It is here to stay. The Cookie() routine is
very complex and does its best to allow access to the
underlying hash structure of the data. This is the best emulation
I could write trying to match the Collections functionality of
cookies in IIS ASP.
For more information on Cookies, please go to the source at
http://home.netscape.com/newsref/std/cookie_spec.html
$Response->Debug(@args)
API Extension. If the Debug config option is set greater than 0,
this routine will write @args out to server error log. refs in @args
will be expanded one level deep, so data in simple data structures
like one-level hash refs and array refs will be displayed. CODE
refs like
$Response->Debug(sub { "some value" });
will be executed and their output added to the debug output.
This extension allows the user to tie directly into the
debugging capabilities of this module.
While developing an app on a production server, it is often
useful to have a separate error log for the application
to catch debugging output separately. One way of implementing
this is to use the Apache ErrorLog configuration directive to
create a separate error log for a virtual host.
If you want further debugging support, like stack traces
in your code, consider doing things like:
$Response->Debug( sub { Carp::longmess('debug trace') };
$SIG{__WARN__} = \&Carp::cluck; # then warn() will stack trace
The only way at present to see exactly where in your script
an error occurred is to set the Debug config directive to 2,
and match the error line number to perl script generated
from your ASP script.
However, as of version 0.10, the perl script generated from the
asp script should match almost exactly line by line, except in
cases of inlined includes, which add to the text of the original script,
pod comments which are entirely yanked out, and <% # comment %> style
comments which have a \n added to them so they still work.
If you would like to see the HTML preceding an error
while developing, consider setting the BufferingOn
config directive to 0.
$Response->End()
Sends result to client, and immediately exits script.
Automatically called at end of script, if not already called.
$Response->ErrorDocument($code, $uri)
API extension that allows for the modification the Apache
ErrorDocument at runtime. $uri may be a on site document,
off site URL, or string containing the error message.
This extension is useful if you want to have scripts
set error codes with $Response->{Status} like 401
for authentication failure, and to then control from
the script what the error message looks like.
For more information on the Apache ErrorDocument mechanism,
please see ErrorDocument in the CORE Apache settings,
and the Apache->custom_response() API, for which this method
is a wrapper.
$Response->Flush()
Sends buffered output to client and clears buffer.
$Response->Include($filename, @args)
This API extension calls the routine compiled from asp script
in $filename with the args @args. This is a direct translation
of the SSI tag
<!--#include file=$filename args=@args-->
Please see the SSI section for more on SSI in general.
This API extension was created to allow greater modularization
of code by allowing includes to be called with runtime
arguments. Files included are compiled once, and the
anonymous code ref from that compilation is cached, thus
including a file in this manner is just like calling a
perl subroutine. The @args can be found in @_ in the
includes like:
# include.inc
<% my @args = @_; %>
As of 2.23, multiple return values can be returned from
an include like:
my @rv = $Response->Include($filename, @args);
$Response->Include(\%cache_args, @sub_args) *CACHE API*
As of version 2.23, output from an include may be
cached with this API and the CONFIG settings CacheDir & CacheDB. This
can be used to execute expensive includes only rarely
where applicable, drastically increasing performance in
some cases.
This API extension applies to the entire include family:
my @rv = $Response->Include(\%cache_args, @include_args)
my $html_ref = $Response->TrapInclude(\%cache_args, @include_args)
$Server->Execute(\%cache_args, @include_args)
For this output cache to work, you must load Apache::ASP
in the Apache parent httpd like so:
# httpd.conf
PerlModule Apache::ASP
The cache arguments are shown here
$Response->Include({
File => 'file.inc',
Cache => 1, # to activate cache layer
Expires => 3600, # to expire in one hour
LastModified => time() - 600, # to expire if cached before 10 minutes ago
Key => $Request->Form, # to cache based on checksum of serialized form data,
Clear => 1, # always executes include & cache output
}, @include_args);
File - include file to execute, can be file name or \$script
script data passed in as a string reference.
Cache - activate caching, will run like normal include without this
Expires - only cache for this long in seconds
LastModified - if cached before this time(), expire
Key - The cache item identity. Can be $data, \$data, \%data, \@data,
this data is serialized and combined with the filename & @include_args
to create a MD5 checksum to fetch from the cache with. If you wanted
to cache the results of a search page from form data POSTed,
then this key could be
{ Key => $Request->Form }
Clear - If set to 1, or boolean true, will always execute the include
and update the cache entry for it.
Motivation: If an include takes 1 second to execute
because of complex SQL to a database, and you can
cache the output of this include because it is not realtime data,
and the cache layer runs at .01 seconds, then you have a
100 fold savings on that part of the script. Site scalability
can be dramatically increased in this way by intelligently
caching bottlenecks in the web application.
Use Sparingly: If you have a fast include, then it may execute faster
than the cache layer runs, in which case you may actually
slow your site down by using this feature. Therefore
try to use this sparingly, and only when sure you really
need it. Apache::ASP scripts generally execute very
quickly, so most developers will not need to use this feature
at all.
$Response->Include(\$script_text, @args)
Added in Apache::ASP 2.11, this method allows for executing ASP scripts
that are generated dynamically by passing in a reference to the script
data instead of the file name. This works just like the normal
$Response->Include() API, except a string reference is passed in
instead of a filename. For example:
<%
my $script = "<\% print 'TEST'; %\>";
$Response->Include(\$script);
%>
This include would output TEST. Note that tokens like
<% and %> must be escaped so Apache::ASP does not try
to compile those code blocks directly when compiling
the original script. If the $script data were fetched
directly from some external resource like a database,
then these tokens would not need to be escaped at all as in:
<%
my $script = $dbh->selectrow_array(
"select script_text from scripts where script_id = ?",
undef, $script_id
);
$Response->Include(\$script);
%>
This method could also be used to render other types of dynamic scripts,
like XML docs using XMLSubs for example, though for complex
runtime XML rendering, one should use something better suited like XSLT.
See the $Server->XSLT API for more on this topic.
$Response->IsClientConnected()
API Extension. 1 for web client still connected, 0 if
disconnected which might happen if the user hits the stop button.
The original API for this $Response->{IsClientConnected}
is only updated after a $Response->Flush is called,
so this method may be called for a refreshed status.
Note $Response->Flush calls $Response->IsClientConnected
to update $Response->{IsClientConnected} so to use this
you are going straight to the source! But if you are doing
a loop like:
while(@data) {
$Response->End if ! $Response->{IsClientConnected};
my $row = shift @data;
%> <%= $row %> <%
$Response->Flush;
}
Then its more efficient to use the member instead of
the method since $Response->Flush() has already updated
that value for you.
$Response->Redirect($url)
Sends the client a command to go to a different url $url.
Script immediately ends.
$Response->TrapInclude($file, @args)
Calls $Response->Include() with same arguments as
passed to it, but instead traps the include output buffer
and returns it as as a perl string reference. This allows
one to postprocess the output buffer before sending
to the client.
my $string_ref = $Response->TrapInclude('file.inc');
$$string_ref =~ s/\s+/ /sg; # squash whitespace like Clean 1
print $$string_ref;
The data is returned as a referenece to save on what
might be a large string copy. You may dereference the data
with the $$string_ref notation.
$Response->Write($data)
Write output to the HTML page. <%=$data%> syntax is shorthand for
a $Response->Write($data). All final output to the client must at
some point go through this method.
$Request Object
The request object manages the input from the client browser, like
posts, query strings, cookies, etc. Normal return results are values
if an index is specified, or a collection / perl hash ref if no index
is specified. WARNING, the latter property is not supported in
ActiveState PerlScript, so if you use the hashes returned by such
a technique, it will not be portable.
A normal use of this feature would be to iterate through the
form variables in the form hash...
$form = $Request->Form();
for(keys %{$form}) {
$Response->Write("$_: $form->{$_}<br>\n");
}
Please see the ./site/eg/server_variables.htm asp file for this
method in action.
Note that if a form POST or query string contains duplicate
values for a key, those values will be returned through
normal use of the $Request object:
@values = $Request->Form('key');
but you can also access the internal storage, which is
an array reference like so:
$array_ref = $Request->{Form}{'key'};
@values = @{$array_ref};
Please read the PERLSCRIPT section for more information
on how things like $Request->QueryString() & $Request->Form()
behave as collections.
$Request->{Method}
API extension. Returns the client HTTP request method, as in
GET or POST. Added in version 2.31.
$Request->{TotalBytes}
The amount of data sent by the client in the body of the
request, usually the length of the form data. This is
the same value as $Request->ServerVariables('CONTENT_LENGTH')
$Request->BinaryRead([$length])
Returns a string whose contents are the first $length bytes
of the form data, or body, sent by the client request.
If $length is not given, will return all of the form data.
This data is the raw data sent by the client, without any
parsing done on it by Apache::ASP.
Note that BinaryRead will not return any data for file uploads.
Please see the $Request->FileUpload() interface for access
to this data. $Request->Form() data will also be available
as normal.
$Request->ClientCertificate()
Not implemented.
$Request->Cookies($name [,$key])
Returns the value of the Cookie with name $name. If a $key is
specified, then a lookup will be done on the cookie as if it were
a query string. So, a cookie set by:
Set-Cookie: test=data1=1&data2=2
would have a value of 2 returned by $Request->Cookies('test','data2').
If no name is specified, a hash will be returned of cookie names
as keys and cookie values as values. If the cookie value is a query string,
it will automatically be parsed, and the value will be a hash reference to
these values.
When in doubt, try it out. Remember that unless you set the Expires
attribute of a cookie with $Response->Cookies('cookie', 'Expires', $xyz),
the cookies that you set will only last until you close your browser,
so you may find your self opening & closing your browser a lot when
debugging cookies.
For more information on cookies in ASP, please read $Response->Cookies()
$Request->FileUpload($form_field, $key)
API extension. The FileUpload interface to file upload data is
stabilized. The internal representation of the file uploads
is a hash of hashes, one hash per file upload found in
the $Request->Form() collection. This collection of collections
may be queried through the normal interface like so:
$Request->FileUpload('upload_file', 'ContentType');
$Request->FileUpload('upload_file', 'FileHandle');
$Request->FileUpload('upload_file', 'BrowserFile');
$Request->FileUpload('upload_file', 'Mime-Header');
$Request->FileUpload('upload_file', 'TempFile');
* note that TempFile must be use with the UploadTempFile
configuration setting.
The above represents the old slow collection interface,
but like all collections in Apache::ASP, you can reference
the internal hash representation more easily.
my $fileup = $Request->{FileUpload}{upload_file};
$fileup->{ContentType};
$fileup->{BrowserFile};
$fileup->{FileHandle};
$fileup->{Mime-Header};
$fileup->{TempFile};
$Request->Form($name)
Returns the value of the input of name $name used in a form
with POST method. If $name is not specified, returns a ref to
a hash of all the form data. One can use this hash to
create a nice alias to the form data like:
# in global.asa
use vars qw( $Form );
sub Script_OnStart {
$Form = $Request->Form;
}
# then in ASP scripts
<%= $Form->{var} %>
File upload data will be loaded into $Request->Form('file_field'),
where the value is the actual file name of the file uploaded, and
the contents of the file can be found by reading from the file
name as a file handle as in:
while(read($Request->Form('file_field_name'), $data, 1024)) {};
For more information, please see the CGI / File Upload section,
as file uploads are implemented via the CGI.pm module. An
example can be found in the installation
samples ./site/eg/file_upload.asp
$Request->Params($name)
API extension. If RequestParams CONFIG is set, the $Request->Params
object is created with combined contents of $Request->QueryString
and $Request->Form. This is for developer convenience simlar
to CGI.pm's param() method. Just like for $Response->Form,
one could create a nice alias like:
# in global.asa
use vars qw( $Params );
sub Script_OnStart {
$Params = $Request->Params;
}
$Request->QueryString($name)
Returns the value of the input of name $name used in a form
with GET method, or passed by appending a query string to the end of
a url as in http://localhost/?data=value.
If $name is not specified, returns a ref to a hash of all the query
string data.
$Request->ServerVariables($name)
Returns the value of the server variable / environment variable
with name $name. If $name is not specified, returns a ref to
a hash of all the server / environment variables data. The following
would be a common use of this method:
$env = $Request->ServerVariables();
# %{$env} here would be equivalent to the cgi %ENV in perl.
$Application Object
Like the $Session object, you may use the $Application object to
store data across the entire life of the application. Every
page in the ASP application always has access to this object.
So if you wanted to keep track of how many visitors there where
to the application during its lifetime, you might have a line
like this:
$Application->{num_users}++
The Lock and Unlock methods are used to prevent simultaneous
access to the $Application object.
$Application->Lock()
Locks the Application object for the life of the script, or until
UnLock() unlocks it, whichever comes first. When $Application
is locked, this guarantees that data being read and written to it
will not suddenly change on you between the reads and the writes.
This and the $Session object both lock automatically upon
every read and every write to ensure data integrity. This
lock is useful for concurrent access control purposes.
Be careful to not be too liberal with this, as you can quickly
create application bottlenecks with its improper use.
$Application->UnLock()
Unlocks the $Application object. If already unlocked, does nothing.
$Application->GetSession($sess_id)
This NON-PORTABLE API extension returns a user $Session given
a session id. This allows one to easily write a session manager if
session ids are stored in $Application during Session_OnStart, with
full access to these sessions for administrative purposes.
Be careful not to expose full session ids over the net, as they
could be used by a hacker to impersonate another user. So when
creating a session manager, for example, you could create
some other id to reference the SessionID internally, which
would allow you to control the sessions. This kind of application
would best be served under a secure web server.
The ./site/eg/global_asa_demo.asp script makes use of this routine
to display all the data in current user sessions.
$Application->SessionCount()
This NON-PORTABLE method returns the current number of active sessions
in the application, and is enabled by the SessionCount configuration setting.
This method is not implemented as part of the original ASP
object model, but is implemented here because it is useful. In particular,
when accessing databases with license requirements, one can monitor usage
effectively through accessing this value.
$Server Object
The server object is that object that handles everything the other
objects do not. The best part of the server object for Win32 users is
the CreateObject method which allows developers to create instances of
ActiveX components, like the ADO component.
$Server->{ScriptTimeout} = $seconds
Not implemented. May never be. Please see the
Apache Timeout configuration option, normally in httpd.conf.
$Server->Config($setting)
API extension. Allows a developer to read the CONFIG
settings, like Global, GlobalPackage, StateDir, etc.
Currently implemented as a wrapper around
Apache->dir_config($setting)
May also be invoked as $Server->Config(), which will
return a hash ref of all the PerlSetVar settings.
$Server->CreateObject($program_id)
Allows use of ActiveX objects on Win32. This routine returns
a reference to an Win32::OLE object upon success, and nothing upon
failure. It is through this mechanism that a developer can
utilize ADO. The equivalent syntax in VBScript is
Set object = Server.CreateObject(program_id)
For further information, try 'perldoc Win32::OLE' from your
favorite command line.
$Server->Execute($file, @args)
New method from ASP 3.0, this does the same thing as
$Response->Include($file, @args)
and internally is just a wrapper for such. Seems like we
had this important functionality before the IIS/ASP camp!
$Server->File()
Returns the absolute file path to current executing script.
Same as Apache->request->filename when running under mod_perl.
ASP API extension.
$Server->GetLastError()
Not implemented, will likely not ever be because this is dependent
on how IIS handles errors and is not relevant in Apache.
$Server->HTMLEncode( $string || \$string )
Returns an HTML escapes version of $string. &, ", >, <, are each
escapes with their HTML equivalents. Strings encoded in this nature
should be raw text displayed to an end user, as HTML tags become
escaped with this method.
As of version 2.23, $Server->HTMLEncode() may take a string reference
for an optmization when encoding a large buffer as an API extension.
Here is how one might use one over the other:
my $buffer = '&' x 100000;
$buffer = $Server->HTMLEncode($buffer);
print $buffer;
- or -
my $buffer = '&' x 100000;
$Server->HTMLEncode(\$buffer);
print $buffer;
Using the reference passing method in benchmarks on 100K of
data was 5% more efficient, but maybe useful for some.
It saves on copying the 100K buffer twice.
$Server->MapInclude($include)
API extension. Given the include $include, as an absolute or relative file name to the current
executing script, this method returns the file path that the include would
be found from the include search path. The include search path is the
current script directory, Global, and IncludesDir directories.
If the include is not found in the includes search path, then undef, or bool false,
is returned. So one may do something like this:
if($Server->MapInclude('include.inc')) {
$Response->Include('include.inc');
}
This code demonstrates how one might only try to execute an include if
it exists, which is useful since a script will error if it tries to execute an include
that does not exist.
$Server->MapPath($url);
Given the url $url, absolute, or relative to the current executing script,
this method returns the equivalent filename that the server would
translate the request to, regardless or whether the request would be valid.
Only a $url that is relative to the host is valid. Urls like "." and
"/" are fine arguments to MapPath, but http://localhost would not be.
To see this method call in action, check out the sample ./site/eg/server.htm
script.
$Server->Mail(\%mail, %smtp_args);
With the Net::SMTP and Net::Config modules installed, which are part of the
perl libnet package, you may use this API extension to send email. The
\%mail hash reference that you pass in must have values for at least
the To, From, and Subject headers, and the Body of the mail message.
The return value of this routine is 1 for success, 0 for failure. If the MailHost
SMTP server is not available, this will have a return value of 0.
You could send an email like so:
$Server->Mail({
To => 'somebody@yourdomain.com.foobar',
From => 'youremail@yourdomain.com.foobar',
Subject => 'Subject of Email',
Body =>
'Body of message. '.
'You might have a lot to say here!',
Organization => 'Your Organization',
CC => 'youremailcc@yourdomain.com.foobar',
BCC => 'youremailbcc@yourdomain.com.foobar',
Debug => 0 || 1,
});
Any extra fields specified for the email will be interpreted
as headers for the email, so to send an HTML email, you
could set 'Content-Type' => 'text/html' in the above example.
If you have MailFrom configured, this will be the default
for the From header in your email. For more configuration
options like the MailHost setting, check out the CONFIG section.
The return value of this method call will be boolean for
success of the mail being sent.
If you would like to specially configure the Net::SMTP
object used internally, you may set %smtp_args and they
will be passed on when that object is initialized.
"perldoc Net::SMTP" for more into on this topic.
If you would like to include the output of an ASP page as the
body of the mail message, you might do something like:
my $mail_body = $Response->TrapInclude('mail_body.inc');
$Server->Mail({ %mail, Body => $$mail_body });
$Server->RegisterCleanup($sub)
non-portable extension
Sets a subroutine reference to be executed after the script ends,
whether normally or abnormally, the latter occurring
possibly by the user hitting the STOP button, or the web server
being killed. This subroutine must be a code reference
created like:
$Server->RegisterCleanup(sub { $main::Session->{served}++; });
or
sub served { $main::Session->{served}++; }
$Server->RegisterCleanup(\&served);
The reference to the subroutine passed in will be executed.
Though the subroutine will be executed in anonymous context,
instead of the script, all objects will still be defined
in main::*, that you would reference normally in your script.
Output written to $main::Response will have no affect at
this stage, as the request to the www client has already completed.
Check out the ./site/eg/register_cleanup.asp script for an example
of this routine in action.
$Server->Transfer($file, @args)
New method from ASP 3.0. Transfers control to another script.
The Response buffer will not be cleared automatically, so if you
want this to serve as a faster $Response->Redirect(), you will need to
call $Response->Clear() before calling this method.
This new script will take over current execution and
the current script will not continue to be executed
afterwards. It differs from Execute() because the
original script will not pick up where it left off.
As of Apache::ASP 2.31, this method now accepts optional
arguments like $Response->Include & $Server->Execute.
$Server->Transfer is now just a wrapper for:
$Response->Include($file, @args);
$Response->End;
$Server->URLEncode($string)
Returns the URL-escaped version of the string $string. +'s are substituted in
for spaces and special characters are escaped to the ascii equivalents.
Strings encoded in this manner are safe to put in urls... they are especially
useful for encoding data used in a query string as in:
$data = $Server->URLEncode("test data");
$url = "http://localhost?data=$data";
$url evaluates to http://localhost?data=test+data, and is a
valid URL for use in anchor <a> tags and redirects, etc.
$Server->URL($url, \%params)
Will return a URL with %params serialized into a query
string like:
$url = $Server->URL('test.asp', { test => value });
which would give you a URL of test.asp?test=value
Used in conjunction with the SessionQuery* settings, the returned
URL will also have the session id inserted into the query string,
making this a critical part of that method of implementing
cookieless sessions. For more information on that topic
please read on the setting
in the CONFIG section, and the SESSIONS section too.
$Server->XSLT(\$xsl_data, \$xml_data)
* NON-PORTABLE API EXTENSION *
This method takes string references for XSL and XML data
and returns the XSLT output as a string reference like:
my $xslt_data_ref = $Server->XSLT(\$xsl_data, \$xml_data)
print $$xslt_data_ref;
The XSLT parser defaults to XML::XSLT, and is configured with the
XSLTParser setting, which can also use XML::Sablotron ( support added in 2.11 ),
and XML::LibXSLT ( support added in 2.29 ).
Please see the CONFIG section for more information on the
XSLT* settings that drive this API. The XSLT setting itself
uses this API internally to do its rendering.
This API was created to allow developers easy XSLT component
rendering without having to render the entire ASP scripts
via XSLT. This will make an easy plugin architecture for
those looking to integrate XML into their existing ASP
application frameworks.
At some point, the API will likely take files as arguments,
but not as of the 2.11 release.