Declaration
TypeLibrary Declarations
#include Directives
**Note:** The Global.asa file must be stored in the root directory of the ASP application, and each application can have only one Global.asa file.
Events in Global.asa
In Global.asa, you can tell the application and session objects what to do when an application/session starts and what to do when it ends. The code that does this is placed in event handlers. A Global.asa file can contain four types of events:
Application_OnStart
This event occurs when the first user requests the first page of the ASP application. It also occurs after the Web server is restarted or the Global.asa file is edited. The "Session_OnStart" event occurs immediately after this event.
Session_OnStart - This event occurs whenever a new user requests his or her first page in the ASP application.
Session_OnEnd - This event occurs whenever a user ends a session. A user's session ends if he or she does not request any page within a specified time (20 minutes by default).
Application_OnEnd - This event occurs after the last user ends his or her session. Typically, it occurs when the Web server stops. This subroutine is used to clean up settings after the application stops, such as deleting records or writing information to a text file.
A Global.asa file might look like this:
**Note:** Since we cannot use ASP's script delimiters in the Global.asa file (<% and %>) to insert scripts, we need to place the subroutines in the HTML
Global.asa can also be used to control page access.
The example below shows how to redirect every new visitor to another page, in this case to a page named "newpage.asp":
You can include functions in the Global.asa file.
In the example below, when the Web server starts, the Application_OnStart subroutine also starts. The Application_OnStart subroutine then calls another subroutine named "getcustomers". The "getcustomers" subroutine opens a database and retrieves a recordset from the "customers" table. This recordset is assigned to an array, which any ASP page can access without querying the database:
Global.asa Example
In this example, we create a Global.asa file that counts the current number of visitors.
When the server starts, Application_OnStart sets the Application variable "visitors" to 0.
Each time a new visitor arrives, the Session_OnStart subroutine adds 1 to the "visitors" variable.
Each time the Session_OnEnd subroutine is triggered, it subtracts 1 from the "visitors" variable.
The Global.asa file:
In the ASP file, display the current number of visitors:
There are <%response.write(Application("visitors"))%> online now!