Home
Главная
Forums
Форум
Your Account
Ваш аккаунт
Web-технологии
HTML, XML, DHTML
JavaScript
SQL
PHP
Perl
SSI
ASP
CSS

Графика
Adobe PhotoShop
Adobe PhotoShop - 2
Macromedia Flash

Компьютеры
Hardware
Мобильные технологии
КПК и ноутбуки

Операционные системы
Unix/Linux
Windows 9x
Windows XP

Стоит посмотреть
  • работа для студентов


  • Качественный дизайн квартир. Качественный дизайн ремонт квартир большая редкость.


  • Нуждаетесь в раскрутке? Закажите вирусный маркетинг и мы возьмем на себя ваши проблемы.


  • Компьютерная помощь


  • intel matrix storage
  • Учебник по SSI (Server Side Includes)

    Технологию 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

     

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

    Пример: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)

     

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

    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


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

    Аргументы:

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

    Пример: 



    fsize


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

    Аргументы:

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

    Пример: [an error occurred while processing this directive]


    flastmod


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

    Аргументы:

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

    Пример: [an error occurred while processing this directive]


    exec

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

    Аргументы:

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

      Пример: 



    config

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

    Аргументы:

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

      Пример:

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

      Пример:

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

      Пример: 


    Форматы представления даты и времени 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'='""'where 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="'"'where 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="'"'where 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="'"'where is one of the following tags.

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

    • 'goto'
    • where
    • 'print' causes text to be printed. The format of the print tag is:
      • 'print "'"'
      • where 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

    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:
    • 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='""' where;

    • 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="'','',''"'where ;

    • 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.
    • is the name which to log into the data source.
    • 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: .

    '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="''"',where:

    • 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:
    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="''"'where;

    • 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: .
    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
    Отправка электронной почты.
    Пример:

    При отработке данного примера будет отправлено электронное письмо (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=" ''"' where
      • := 'ON' to enable debugging
      • := '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.


    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' '"''"' '"''"'

    where:

    • is the first operand of a logical comparison statement
    • is the second operand of a logical comparison statement
    • is the logical comparison method ['==', '!=','<', '>', '!<', '!>']
    • 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'
      • where
    • 'print' causes text to be printed. The format of the print tag is:
      • 'print'
      • where 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.

    • This should not print

    • 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).

    • The operands are not equal.

    • operands are equal.

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

    • You are not using Mosaic

    • You are using Mosaic

    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.


    goto

    Команда goto оператор перехода на маетку label.
    Формат команды:

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

    Пример.

    This line will not print.

    This line will print.

    Замечание: Между сиволами

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

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

    Замечание: Между сиволами

    This line will not print because the document has been truncated and transmission to the client is terminated.



    Дополнительно на данную тему:

    SSI в примерах
    SSI (часть 1)
    SSI (часть 2)
    Мощь SSI
    SSI: вкусно и полезно
    CGI+SSI - пример счетчика

    Назад | Начало | Наверх
    Rambler's Top100