Учебник по SSI (Server Side Includes)

Home ] Up ] Содержание подраздела сайта ]

 

Технологию SSI поддерживают почти все сервера: Apache, Netscape, Spry Web и Microsoft Internet Information Server. По сути это препроцессор, то есть перед выдачей страницы клиенту производится обработка ее сервером.

SSI+ это более расширенная версия SSI.

Поддержка этой технологии связанна с специальной конфигурацией WWW сервера и протокола HTTP.

Директивы SSI позволяют использовать в HTML документах такие возможности как: выполнение других программ, получение информации о файлах, переменных среды. SSI позволяет в отдельных случаях добиваться довольно многого обходясь без написания CGI..

Если сервер не воспринимает режим SSI, то есть команды SSI не обрабатываются, то они воспринимаются как комментарий и выводятся пользователю как есть.

Какой тип файлов обрабатывается SSI зависит от конфигурирования сервера, по умолчанию обрабатываются файлы с расширением .shtml .sht , но можно настроить сервер и на обработку файлов .htm .html. Для этого нужно в файле испоганить настройки apache или для ограниченного в правах пользователя вбить в файл .htaccess :
    AddType text/html .htm .html .shtml
    AddHandler server-parsed .htm .html .shtml
    Options +Includes

  Формат команды SSI

 <!--#команда параметр(ы)="аргумент"-->
некоторые команды имеют еще и подкоманды:

&&подкоманда&&

 

Основные команды SSI

'echo' Вставка в документ переменных среды (браузер, дата, имя документа, ...).
'include' Включение файла в HTML документ.
'fsize' Включение размера файла в HTML документ.
'flastmod'  Включение даты последней модификации файла в HTML документ.
'exec' Выполнение внешнего исполняемого файла (CGI программы). Выходной поток данных (стандартный вывод) этой программы включается в документ.
'config' Установка параметров для SSI+ команд.
'odbc' Обращение к внешней ODBC СУБД.
'email' Отправка электронной почты или представление формы.
'if' Условный оператор, управляющий выполнением других команд SSI и вывода документа.
'goto' Оператор перехода на определенную SSI метку ('label').
'label' Метка в документе.
'break' Остановка вывода документа.

 


echo

  <!--#echo var="переменная_среды"-->

Предназначена для вставки в документ значений специальных переменных SSI, а также других переменных среды.

Пример:

 <!--#echo var="HTTP_USER_AGENT"-->

наиболее употребимые переменные среды:

DOCUMENT_NAME локальное имя файла
DOCUMENT_URI URL файла
QUERY_STRING_UNESCAPED Строка, полученная от клиента, содержащая все метасимволы командного процессора
DATE_LOCAL Текущая локальная дата и время
DATE_GMT Текущая дата и время по Гринвичу
LAST_MODIFIED Дата и время последнего изменения текущего файла
REMOTE_ADDR IP адрес удаленного клиента
QUERY_STRING Строка, полученная от клиента
SERVER_SOFTWARE Имя HTTP server software
SERVER_NAME Имя компьютера, на котором работает WWW сервер
GATEWAY_INTERFACE Имя и версия Common Gateway Interface served WWW (HTTP) сервера (name/version)
SERVER_PROTOCOL Имя и версия HTTP сервера (name/version)
SERVER_PORT IP порт WWW (HTTP) сервера
REQUEST_METHOD Тип метода запроса к серверу
PATH_INFO Виртуальный путь, указанный в запросе (путь от базовой директории WWW сервера)
PATH_TRANSLATED Полный путь, указанный в запросе
SCRIPT_NAME Имя программы для выполнения в CGI запросе
REMOTE_HOST Имя компьютера удаленного клиента
AUTH_TYPE Переменная для определения авторизованного метода доступа к серверу (authentication method)
REMOTE_USER Имя пользователя для авторизованного метода доступа
REMOTE_IDENT Имя удаленного клиента, используемое для идентификации пользователя, согласно спецификации RFC931
CONTENT_TYPE Тип передачи данных от клиета по методам POST или PUT
CONTENT_LENGTH Длина в байтах переданных данных по методам POST или PUT
HTTP_ACCEPT Список, разделенный запятыми, MIME типов, понимаемых браузером клиента
HTTP_USER_AGENT Имя браузера клиента (browser software).
HTTP_REFERER URL адрес HTML документа из которого сделан запрос клиентом
HTTP_FROM Имя (подобное имени Е-mail address) удаленного клиента
HTTP_FORWARDED Имя Proxy Server, через который общается клиент
ACCEPT_LANGUGE Список языков доступных для копьютера клиента
HTTP_COOKIE Содержение ответа клиента на запрос от сервера (см. ниже)

 


include

<!--#include file="путь"-->
<!--# include virtual="путь"-->

Предназначена для вставки содержимого файла в текущий документ, также может использоваться для вывода результатов работы скрипта.

Аргументы:

  • file - Путь к файлу, относительно текущей директории. (То есть не может быть абсолютным путем к файлу (начинаться с / или содержать ../).
  • virtual - Виртуальный (фактический) путь к документу на сервере. Он может начинатся с /, но должен быть на том же сервере.

Пример: 
<!--#include file="docext.html"-->
<!--#include virtual="/counters/spylog.txt"-->
<!--#include virtual="/cgi-bin/counter.pl" -->


fsize

<!--#fsize file="путь"-->
<!--#fsize virtual="путь"-->

Выводит размер файла, формат выдачи может быть изменен командой config

Аргументы:

  • file - Путь к файлу, относительно текущей директории. (То есть не может быть абсолютным путем к файлу (начинаться с / или содержать ../).
  • virtual - Виртуальный (фактический) путь к документу на сервере. Он может начинатся с /, но должен быть на том же сервере.

Пример:

<!--#fsize virtual="ssi.htm"-->


flastmod

<!--#flastmod file="путь"-->
<!--#flastmod virtual="путь"-->

Выводит дату/время последнего изменения файла, формат выдачи может быть изменен командой config

Аргументы:

  • file - Путь к файлу, относительно текущей директории. (То есть не может быть абсолютным путем к файлу (начинаться с / или содержать ../).
  • virtual - Виртуальный (фактический) путь к документу на сервере. Он может начинатся с /, но должен быть на том же сервере.

Пример:

<!--#flastmod virtual="ssi.htm"-->


exec

<!--#exec cgi="/cgi-bin/counter.pl"-->

Вызывает внешние программы, формат выдачи может быть изменен командой config.

Аргументы:

  • cmd - вызов исполняемых программ в UNIX shell.
  • cgi - вызов CGI скрипта.

  Пример: 

<!--#exec cmd="/bin/finger vasjapjatkin@mail.ru"-->
<!--#exec cgi="/cgi-bin/puperscript.cgi"-->


config

Модифицирует формат вывода для других команд.

Аргументы:

errmsg - формат сообщения об ошибке, которое выдается когда обработчик SSI+ обнаруживает ошибки. Для SSI+ также можно использовать onerr.

  Пример: <!--#config errmsg="Ошибка обработки SSI запроса"-->

sizefmt - формат информации об объеме файла. Допустимые значения sizefmt - bytes или addrev. Они задают округление значения объема файла до ближайшего килобайта.

  Пример: <!--#config sizefmt="addrev"-->

timefmt  - формат значений даты/времени.

  Пример: 

<!--#config timefmt="%D %r"-->
<!--#flastmode file="ssi.htm"-->

Форматы представления даты и времени SSI

Код Значение Пример
%a День недели в сокращенном виде Sun
%A День недели Sunday
%b Месяц в сокращенном виде (также %h) Jan
%B Месяц  Januar
%d Дата  01
%D Дата в формате %m/%d/%y 06/23/99
%e Дата 1
%H Время в часах в 24-часовой системе 13
%I Время в часах в 12-часовой системе 01
%j День года (десятичное число) 360
%m Номер месяца 11
%M Количество минут 08
%p AM|PM AM
%r Время в формате %I:%M:%p 09:21:13 PM
%S Количество секунд 09
%T Время в 24-часовой системе в формате %H:%M:%S 12:22:40
%U Порядковый номер недели года (также%W) 37
%w Порядковый номер дня недели (начиная с Sunday=0) 2
%y Год века 96
%Y Год 1996
%z Часовой пояс EST

'cmdecho' The cmdecho variable is used to set the output option of subsequent exec..cmd tokens. The format is 'cmdecho'='"<onoroff>"'where <onoroff> is either 'ON' or 'OFF'. When the SSI+ parsing engine encounters an exec..cmd token it executes the command. If the command returns output then that output may be echoed into the HTML document or it may be ignored. The format of the data echoed is dependent on the presence or absence of config..cmdprefix and config..cmdpostfix tokens in the document. In the absence of config..cmdprefix and config..cmdpostfix tokens the output will be echoed exactly as returned with no formatting and no special character interpretation. In the presence of config..cmdprefix and/or config..cmdpostfix tokens the output will be formatted and interpreted. To activate echoing set cmdecho to 'ON' otherwise set it to 'OFF'. The default is 'OFF'.

'cmdprefix' The cmdprefix variable is used to set the string prefixed to each line out output from subsequent exec..cmd tokens. The format is 'cmdprefix="'<string>"'where <string> is any character string and/or HTML format tags. When the SSI+ parsing engine encounters an exec..cmdtoken it executes the command. If the command returns output then that output may be echoed into the HTML document or it maybe ignored. If the output is echoed (see 'cmdecho' above),then each line output from the executable will be prefixed with the string supplied before being echoed into the HTML document.

'cmdpostfix' The cmdpostfix variable is used to set the string appended to the end of each line out output from subsequent exec..cmd tokens. The format is 'cmdpostfix="'<string>"'where <string> is any character string and/or HTML format tags. When the SSI+ parsing engine encounters an exec..cmdtoken it executes the command. If the command returns output then that output may be echoed into the HTML document or it maybe ignored. If the output is echoed (see 'cmdecho' above),then each line output from the executable will be appended with the string supplied before being echoed into the HTML document.

'onerr' The onerr variable is used to set the action to be taken when the SSI+ engine encounters an error. The format is 'onerr="'<action>"'where <action> is one of the following tags.

'goto' causes a jump to a label token (see below). The format of the goto tag is:

  • 'goto' <label>
  • where <label> is the name of a label defined in a subsequent label tag (see below).
  • 'print' causes text to be printed. The format of the print tag is:
    • 'print "'<text>"'
    • where <text> is any HTML text or tag.
  • 'error' causes the current config..error message to be printed.
  • 'break' causes termination of the HTML document transmission to the client.
  • 'errorbreak' causes the current config..error message to be printed, and then causes termination of the HTML document transmission to the client.
  • 'printbreak' causes text to be printed, and then causes termination of the HTML document transmission to the client. The format of the printbreak tag is the same as the format of the print tag.

Example. The following token on an HTML document sets the SSI+ error action to print a message and terminate the document. From this point on down when an error occurs in the SSI+ parsing engine the message will be inserted into the HTML document at the location of the offending SSI+ statement, and the document will be terminated

  • <!--#config onerr="printbreak "Sorry, we encountered an error while processing your document."" -->

Example. Suppose you wish to create an HTML document that performs a 'PING' operation on address '204.96.64.171' and then echo the results back to the client browser, with each line echoed as an element in an unnumbered list.

  • Insert the following lines into your HTML document:
    • <UL>
    • <!--#config cmdecho="ON" -->
    • <!--#config cmdprefix="<LI>" -->
    • <!--#exec cmd="ping 204.96.64.171 -w 20000" -->
    • </UL>
  • When the document is accessed by a remote browser the output would look something like this:
    • Pinging 204.96.64.171 with 32 bytes of data:
    • Reply from 204.96.64.171: bytes=32 time<10ms TTL=32
    • Reply from 204.96.64.171: bytes=32 time<10ms TTL=32
    • Reply from 204.96.64.171: bytes=32 time<10ms TTL=32
    • Reply from 204.96.64.171: bytes=32 time<10ms TTL=32




odbc

Notice! Due to some problems with the MS ODBC drivers we are phasing out the support of the SSI+ ODBC tags. To impliment ODBC with WebQuest we are using CScript with our WQODBC.DLL. For more information on CScript and ODBC, check out the Guestbook tutorial. The SSI+ ODBC tags will not exist in WebQuest 3.0.

The odbc tag provides for querying and updating odbc databases. Four variables are defined for the odbc token; 'debug', 'connect', 'statement', and 'format'.

'debug' variable

The debug variable is used to set the SSI+ engine into debug mode. Debug mode provides diagnostics of a highly detailed nature from both the SSI engine itself and the local ODBC engine. Debug messages appear on the returned HTML document at the position at which the errors occur. The debug variable should be used only for development and must be removed before production. When the debug variable is present a warning message will appear indicating it's presence, this message is benign and will not affect any other aspect of the SSI+ engine. The format of the debug variable is : 'debug='"<debugstring>"' where;

  • <debugstring> is any string and is reserved for future use.


'connect' variable

The connect variable is used to connect to a pre-existing odbc data source, to allow for subsequent statement tag operations on that data source. The format of the connect variable is 'connect="'<datasource>','<username>','<password>'"'where ;

  • <datasource> is the name odbc data source as defined on the local system in the odbc configuration utility. CAUTION! the account under which the server is run must be granted permission to access the data source.
  • <user name> is the name which to log into the data source.
  • <password> is the password with which to access the data source.

Example. To connect to a data source called 'odbcsht' as user 'dufus' and password 'dorkboy', one would use the following statement: <!--#odbc connect="odbcsht,dufus,dorkboy"-->.

'statement' variable

The statement variable is used to submit a Transact SQL statement to the odbc data source. The format of a statement variable is as follows: 'statement="'<SQLStatement>'"',where:

  • <SQL Statement> is any Transact SQL statement as defined in odbc and SQL reference text and help files.

Example. Suppose one wanted to query the 'CUSTOMERS' table from the above connected 'odbcsht' database to return all rows and display each row on a separate line. One may use the following sequence of statements:

  1. Connect to the database with a connect token as described above.
  2. Setup the output format with a statement token as described below.
  3. Execute the query: <!--#odbc statement="SELECT NAME, AGE, VISCOSITY FROM CUSTOMERS ORDER BY 3, 2, 1" -->
  4. Each row of the database will the be inserted into the HTML page per the format statement as demonstrated below.


'format' variable

The format variable is used to provide a template for the format of data that is returned from and odbc query. Use this variable to set up the appearance of data that will be returned from subsequent statement tag operations that return data from a database (i.e. the SQL statement 'SELECT'). The format of the format variable is 'format="'<cprintfstatement>'"'where;

  • <cprintfstatement> is a standard C language printf format string with the restriction of only allowing string (%s) insertions. The user is referred to any C language text for a description of this format. The number of instances of %s must be equal to the number of fields selected in a the subsequent SQL SELECT statement token.

Example. Suppose one wanted to query the 'CUSTOMERS' table from the above connected 'odbcsht' database to display the columns 'name', 'age', and 'viscosity' with each row on a separate line. One may use the following sequence of statements:

  1. Connect to the database with a connect token as described above.
  2. Setup the output format: <!--#obdc format="<P>Thecustomer's name is %s, and he is %s years old, he prefers a motor oil with SPF %s viscosity" -->.
  3. Execute the query with a statement token as described above.
  4. Each row of the database will the be inserted into the HTML page per the format statement. For example if the database has 3 rows the HTML output would look something like this:
  • Customer's name is Conan, and he is 29 years old, he prefers a motor oil with SPF 15 viscosity
  • Customer's name is Kevin, and he is 45 years old, he prefers a motor oil with SPF 30 viscosity
  • Customer's name is Alan, and he is 43 years old, he prefers a motor oil with SPF 50 viscosity


email
Отправка электронной почты.
Пример:

<!--#email tohost="www.ict.nsk.su" message="Thanks for the HTML" toaddress="www@www.ict.nsk.su" subject="The SSI"-->

При отработке данного примера будет отправлено электронное письмо (e-mail), содержание которого задано атрибутом message, по адресу, определенному атрибутом toaddress, если данный адрес и host, заданный атрибутом tohost (данный атрибут может отсутсвовать), реально существует.

The email tag provides for sending an Email whenever an HTML page is accessed or an HTML form submitted. The nature of the variables below is defined in RFC 733. The variables 'fromhost', 'tohost', 'fromaddress' and 'toaddress' are required, all others are optional.

  1. 'debug' enables advanced diagnostics. This variable should only be used during development. The format of this variable is 'debug=" '<OnOrOff>'"' where
    • <OnOrOff> := 'ON' to enable debugging
    • <OnOrOff> := 'OFF' to disable debugging, this is the default action if the debug variable is omitted.
  2. 'fromhost' defines the name of the smtp host sending the mail.
  3. 'tohost' defines the name of the smtp host the mail will be sent to.
  4. 'fromaddress' defines the email address from party.
  5. 'toaddress' defines the email address of the recipient party.
  6. 'message' defines the message body to be sent.
  7. 'subject' defines the subject field of the message to be sent.
  8. 'sender' defines the email address sending party.
  9. 'replyto' defines the email address to which replies should be sent.
  10. 'cc' defines the courtesy copy email addresses.
  11. 'inreplyto' defines the inreplyto field of the message to be sent.
  12. 'id' defines the id field of the message to be sent.

Example. The following document send an email with debugging enabled. Supposewe have a form with datum : [First, Last, Middle Initial, Company,Address1, Address2, City, State, Zip, Country, Phone, Fax, Request,Urgency, ReplyMethod; Email, Subject, Message] we may post thatform to an HTML document containing the following fragment tosend an email.

  • <!--#email debug="ON" fromhost="www.theworld.com" tohost="mailbox.theworld.com" message="First -&&First&&, Last - &&Last&&,MI- &&Middle Initial&&, Company - &&Company&&, Address - &&Address1&&, &&Address2&&, &&City&&, &&State&&, &&Zip&&, &&Country&&, Phone - &&Phone&&,Fax - &&Fax&&, Request &&Urgency &&via&& ReplyMethod&&, Message - &&Message&& "fromaddress="&&EMail&&" toaddress="markw@mailbox.theworld.com" subject="WebMan - &&Subject&&" sender="&&EMail&& "replyto="&&EMail&&" cc=" " inreplyto="A WebMan Automated E-Mail" id="WebManEMail" -->


if

The if tag provides for conditional execution of SSI operations, and conditional printing of HTML text, based on logical comparisons. The format of the if tag is :

'if' '"'<operand1>'"' <operator> '"'<operand2>'"'<operation>

where:

  • <operand1> is the first operand of a logical comparison statement
  • <operand2> is the second operand of a logical comparison statement
  • <operator> is the logical comparison method ['==', '!=','<', '>', '!<', '!>']
  • <operation> is the action to take if the logical comparison evaluates to TRUE ['goto', 'print', 'error', 'break', 'errorbreak', 'printbreak']

The operands may be any string or number (integer or floating point). In the event that both operands are numbers the comparison will be based on the value of the numbers. In the event that one or both of the operands and not numbers, the comparison will be based on the alphabetic order of the operands.

The special case of the NULL operand is defined by two quotes with no characters between them. The NULL operand may used to check for the existence of form data from the remote client (see example below).

  • The operator defines what kind of comparison is performed on the operands:
  • '==' The equalto operator evaluates to TRUE if the operands are equal to each other.
  • '!=' The notequalto operator evaluates to TRUE if the operands are not equal to each other.
  • '<' The lessthan operator evaluates to TRUE if operand1 is less than operand2.
  • '>' The greaterthan operator evaluates to TRUE if operand1 is greater than operand2
  • '!<' The notlessthan operator evaluates to TRUE if operand1 is not less than operand2
  • '!>' The notgreaterthan operator evaluates to TRUE if operand1 is not greater than operand2
  • 'hasstring' The hasstring operator returns TRUE is the text string in operand2 is found in the operand1 string.

In the event that the logical comparison evaluates to FALSE, nothing happens, If the logical comparison evaluates to TRUE then one of the following operations may be performed:

  • 'goto' causes a jump to a label token (see below).The format of the goto tag is:
    • 'goto' <label>
    • where <label> is the name of a label defined in a subsequent label tag (see below).
  • 'print' causes text to be printed. The format of the print tag is:
    • 'print' <text>
    • where <text> is any HTML text or tag.
  • 'error' causes the current config..error message to be printed.
  • 'break' causes termination of the HTML document transmission to the client.
  • 'errorbreak' causes the current config..error message to be printed, and then causes termination of the HTML document transmission to the client.
  • 'printbreak' causes text to be printed, and then causes termination of the HTML document transmission to the client. The format of the printbreak tag is the same as the format of the print tag.

Example. The following document fragment compares two numbers, if the operands are not equal then a goto will jump to a label.

  • <!--#if "10" != "20" goto testlabel-->
  • <P>This should not print
  • <!--#label ="testlabel" -->
  • <P>This should print

Example. The following document fragment demonstrates conditional execution based on data delivered from an HTML form. Suppose we have two form datum called 'formdata1' and 'formdata2' and we wish to compare them. The following document fragment compares the two operands, if the operands are equal then a goto will jump to a label. Otherwise the next line will print and the document will terminate on a break token (see below).

  • <!--#if "&&formdata1&&" == "&&formdata2&&" goto testlabel -->
  • <P>The operands are not equal.
  • <!--#break -->
  • <!--#label ="testlabel" -->
  • <P>operands are equal.

Example. The following document fragment prints two different statements depending on whether or not the client agent is NCSA Mosaic.

  • <!--#if "&&HTTP_USER_AGENT&&" hasstring "Mosaic" goto mosaiclabel -->
  • <P>You are not using Mosaic
  • <!--#goto ="defaultlabel" -->
  • <!--#label ="mosaiclabel" -->
  • <P>You are using Mosaic
  • <!--#label ="defaultlabel" -->

Example. Suppose we have a form with amongst other things a field named "BOO" and we wish to make sure that the remote client user enterted data into the "BOO" field before submitting the form. The following document fragment checks for the presence of data in the "BOO" field, if data exists then nothing happens, if data does not exist then a message will be displayed and the document will terminate.

  • <!--#if "&&BOO&&" == "" printbreak "<P>You must provide data for the BOO field, please resubmit." -->


goto

Команда goto оператор перехода на маетку label.
Формат команды:
<!--#goto ="<label>"-->

где <label> имя метки, определенное командой label.

Пример.

<!--#goto ="testlabel" --> <P>This line will not print. <!--#label ="testlabel" --> <P>This line will print.

Замечание: Между сиволами <!--#goto и знаком = обязательно должен стоять пробел.


label

Команда label устанавливает метку в документе, которая используется командами goto или if..goto
Формат команды:
<!--#label ="<label>"-->

где <label> строка из не более чем 51 символа без пробелов, идентиифицирующая место в документе.

Задание метки не влияет на форматирование документа.

Замечание: Между сиволами <!--#label и знаком = обязательно должен стоять пробел.


break

Команда break останавливает вывод документа как только встречается.

Пример. Следующий пример демонстрирует работу команды break.

<P>This line will print. <!--#break --> <P>This line will not print because the document has been truncated and transmission to the client is terminated.

 

 


last edited 15/03/02 TopList