Сценарии на стороне сервера

From Wikipedia, the free encyclopedia

From Wikipedia, the free encyclopedia

Languages used in server side scripting.

Server-side scripting is a technique used in web development which involves employing scripts on a web server which produces a response customized for each user’s (client’s) request to the website. The alternative is for the web server itself to deliver a static web page. Scripts can be written in any of a number of server-side scripting languages that are available (see below). Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.

Server-side scripting is often used to provide a customized interface for the user. These scripts may assemble client characteristics for use in customizing the response based on those characteristics, the user’s requirements, access rights, etc. Server-side scripting also enables the website owner to hide the source code that generates the interface, whereas, with client-side scripting, the user has access to all the code received by the client. A downside to the use of server-side scripting is that the client needs to make further requests over the network to the server in order to show new information to the user via the web browser. These requests can slow down the experience for the user, place more load on the server, and prevent the use of the application when the user is disconnected from the server.

When the server serves data in a commonly used manner, for example, according to the HTTP or FTP protocols, users may have their choice of a number of client programs (most modern web browsers can request and receive data using both of those protocols). In the case of more specialized applications, programmers may write their own server, client, and communications protocol, that can only be used with one another.

Programs that run on a user’s local computer without ever sending or receiving data over a network are not considered clients, and so the operations of such programs would not be considered client-side operations.

History[edit]

Netscape introduced an implementation of JavaScript for server-side scripting with Netscape Enterprise Server, first released in December, 1994 (soon after releasing JavaScript for browsers).[1][2]

Server-side scripting was later used in early 1995 by Fred DuFrense while developing the first website for Boston, MA television station WCVB. The technology is described in US patent 5835712. The patent was issued in 1998 and is now owned by Open Invention Network (OIN). In 2010 OIN named Fred DuFresne a «Distinguished Inventor» for his work on server-side scripting.

Explanation[edit]

In the earlier days of the web, server-side scripting was almost exclusively performed by using a combination of C programs, Perl scripts, and shell scripts using the Common Gateway Interface (CGI). Those scripts were executed by the operating system, and the results were served back by the webserver. Many modern web servers can directly execute on-line scripting languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via extension modules (e.g. mod_perl or mod_php) to the webserver. For example, WebDNA includes its own embedded database system. Either form of scripting (i.e., CGI or direct execution) can be used to build up complex multi-page sites, but direct execution usually results in less overhead because of the lower number of calls to external interpreters.

Dynamic websites sometimes use custom web application servers, such as Glassfish, Plack and Python’s «Base HTTP Server» library, although some may not consider this to be server-side scripting. When using dynamic web-based scripting techniques, developers must have a keen understanding of the logical, temporal, and physical separation between the client and the server. For a user’s action to trigger the execution of server-side code, for example, a developer working with classic ASP must explicitly cause the user’s browser to make a request back to the webserver.

Server-side scripts are completely processed by the servers instead of clients. When clients request a page containing server-side scripts, the application server processes the scripts and returns an HTML page to the client.

Server-side rendering[edit]

In the beginning of the web content was generated purely on the back end. After the big adoption of front end single-page applications, a new approach was introduced to generate the HTML using the client application, but on the back end. Examples of frameworks that use SSR are Next.js, Nuxt.js and Nest.js. They use React.js, Vue.js, and Angular, respectively, to generate the content of the server.

Server-side generation[edit]

Another similar to SSR technique of generating content for a website is using Server-side generation. This technique use application that create static html pages and then those files are send to the server. File generation can happen on completely different computer for example using continuous delivery. Example of SSG tools are Jekyll, Gatsby or Eleventy. Those sites are often hosted on Netlify or GitHub pages. GitHub also supports Jekyll projects where it automatically build the site when changes are added to git.

Languages[edit]

There are a number of server-side scripting languages available, including:

  • ActiveVFP (*.avfp)
  • ASP (*.asp)
  • ASP.NET Web Forms (*.aspx)
  • ASP.NET Web Pages (*.cshtml, *.vbhtml)
  • ColdFusion Markup Language (*.cfm)
  • Go (*.go)
  • Google Apps Script (*.gs)
  • Hack (*.php)
  • Haskell (*.hs) (example: Yesod)
  • Java (*.jsp, *.do) via JavaServer Pages
  • JavaScript using Server-side JavaScript (*.ssjs, *.js) (example: Node.js)
  • Lasso (*.lasso)
  • Lua (*.lp *.op *.lua)
  • Parser (*.p)
  • Perl via the CGI.pm module (*.cgi, *.ipl, *.pl)
  • PHP (*.php, *.php3, *.php4, *.phtml)
  • Python (*.py) (examples: Pyramid, Flask, Django)
  • R (*.rhtml)
  • Ruby (*.rb, *.rbw) (example: Ruby on Rails)
  • Tcl (*.tcl)
  • WebDNA (*.dna,*.tpl)
  • Progress WebSpeed (*.r,*.w)

See also[edit]

  • Client-side scripting
  • Content management system (CMS)
  • Edge Side Includes
  • JSP
  • Node.js
  • Next.js
  • Outline of web design and web development
  • Perl/Plack
  • PHP
  • Server Side Includes (SSI)
  • Web development

References[edit]

  1. ^ «Server-Side JavaScript Guide». Netscape Communications Corporation. 1998. Retrieved 2012-04-25.
  2. ^ Mike Morgan (1996). «Using Netscape™ LiveWire™, Special Edition». Que.

External links[edit]

  • Server-side scripting at Curlie;

From Wikipedia, the free encyclopedia

Languages used in server side scripting.

Server-side scripting is a technique used in web development which involves employing scripts on a web server which produces a response customized for each user’s (client’s) request to the website. The alternative is for the web server itself to deliver a static web page. Scripts can be written in any of a number of server-side scripting languages that are available (see below). Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.

Server-side scripting is often used to provide a customized interface for the user. These scripts may assemble client characteristics for use in customizing the response based on those characteristics, the user’s requirements, access rights, etc. Server-side scripting also enables the website owner to hide the source code that generates the interface, whereas, with client-side scripting, the user has access to all the code received by the client. A downside to the use of server-side scripting is that the client needs to make further requests over the network to the server in order to show new information to the user via the web browser. These requests can slow down the experience for the user, place more load on the server, and prevent the use of the application when the user is disconnected from the server.

When the server serves data in a commonly used manner, for example, according to the HTTP or FTP protocols, users may have their choice of a number of client programs (most modern web browsers can request and receive data using both of those protocols). In the case of more specialized applications, programmers may write their own server, client, and communications protocol, that can only be used with one another.

Programs that run on a user’s local computer without ever sending or receiving data over a network are not considered clients, and so the operations of such programs would not be considered client-side operations.

History[edit]

Netscape introduced an implementation of JavaScript for server-side scripting with Netscape Enterprise Server, first released in December, 1994 (soon after releasing JavaScript for browsers).[1][2]

Server-side scripting was later used in early 1995 by Fred DuFrense while developing the first website for Boston, MA television station WCVB. The technology is described in US patent 5835712. The patent was issued in 1998 and is now owned by Open Invention Network (OIN). In 2010 OIN named Fred DuFresne a «Distinguished Inventor» for his work on server-side scripting.

Explanation[edit]

In the earlier days of the web, server-side scripting was almost exclusively performed by using a combination of C programs, Perl scripts, and shell scripts using the Common Gateway Interface (CGI). Those scripts were executed by the operating system, and the results were served back by the webserver. Many modern web servers can directly execute on-line scripting languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via extension modules (e.g. mod_perl or mod_php) to the webserver. For example, WebDNA includes its own embedded database system. Either form of scripting (i.e., CGI or direct execution) can be used to build up complex multi-page sites, but direct execution usually results in less overhead because of the lower number of calls to external interpreters.

Dynamic websites sometimes use custom web application servers, such as Glassfish, Plack and Python’s «Base HTTP Server» library, although some may not consider this to be server-side scripting. When using dynamic web-based scripting techniques, developers must have a keen understanding of the logical, temporal, and physical separation between the client and the server. For a user’s action to trigger the execution of server-side code, for example, a developer working with classic ASP must explicitly cause the user’s browser to make a request back to the webserver.

Server-side scripts are completely processed by the servers instead of clients. When clients request a page containing server-side scripts, the application server processes the scripts and returns an HTML page to the client.

Server-side rendering[edit]

In the beginning of the web content was generated purely on the back end. After the big adoption of front end single-page applications, a new approach was introduced to generate the HTML using the client application, but on the back end. Examples of frameworks that use SSR are Next.js, Nuxt.js and Nest.js. They use React.js, Vue.js, and Angular, respectively, to generate the content of the server.

Server-side generation[edit]

Another similar to SSR technique of generating content for a website is using Server-side generation. This technique use application that create static html pages and then those files are send to the server. File generation can happen on completely different computer for example using continuous delivery. Example of SSG tools are Jekyll, Gatsby or Eleventy. Those sites are often hosted on Netlify or GitHub pages. GitHub also supports Jekyll projects where it automatically build the site when changes are added to git.

Languages[edit]

There are a number of server-side scripting languages available, including:

  • ActiveVFP (*.avfp)
  • ASP (*.asp)
  • ASP.NET Web Forms (*.aspx)
  • ASP.NET Web Pages (*.cshtml, *.vbhtml)
  • ColdFusion Markup Language (*.cfm)
  • Go (*.go)
  • Google Apps Script (*.gs)
  • Hack (*.php)
  • Haskell (*.hs) (example: Yesod)
  • Java (*.jsp, *.do) via JavaServer Pages
  • JavaScript using Server-side JavaScript (*.ssjs, *.js) (example: Node.js)
  • Lasso (*.lasso)
  • Lua (*.lp *.op *.lua)
  • Parser (*.p)
  • Perl via the CGI.pm module (*.cgi, *.ipl, *.pl)
  • PHP (*.php, *.php3, *.php4, *.phtml)
  • Python (*.py) (examples: Pyramid, Flask, Django)
  • R (*.rhtml)
  • Ruby (*.rb, *.rbw) (example: Ruby on Rails)
  • Tcl (*.tcl)
  • WebDNA (*.dna,*.tpl)
  • Progress WebSpeed (*.r,*.w)

See also[edit]

  • Client-side scripting
  • Content management system (CMS)
  • Edge Side Includes
  • JSP
  • Node.js
  • Next.js
  • Outline of web design and web development
  • Perl/Plack
  • PHP
  • Server Side Includes (SSI)
  • Web development

References[edit]

  1. ^ «Server-Side JavaScript Guide». Netscape Communications Corporation. 1998. Retrieved 2012-04-25.
  2. ^ Mike Morgan (1996). «Using Netscape™ LiveWire™, Special Edition». Que.

External links[edit]

  • Server-side scripting at Curlie;

Web-сервер
обрабатывает серверную сторону среды
сетевых сообщений, от­вечая на
разнообразные HTTP-запросы,
обращенные к нему. Серверы могут либо
напрямую возвращать различные файловые
объекты, такие как HTML-документы,
изображения, мультимедийные файлы,
сценарии или таблицы, либо запускать
исполняемые программы, которые возвращают
аналогичный результат. В этом смысле
Web-сервер
действует одновременно и как файло­вый
сервер, и как сервер приложений. Сейчас,
прежде чем обратиться к се-

Web-серверы

Как
и Web-браузер,
Web-сервер
составляет среды каждой Web-транзакции.
Термин «Web-сервер»
в обыденном понимании включает как
аппаратное, так и программное обеспечение.
Основной вопрос, связанный с аппаратной
частью, заключается в том, способен ли
Web-сервер
справляться с требова­ниями по части
памяти, дискового пространства и сетевого
входа/выхода, проистекающими из трафика
сайта. Взаимодействие операционных
систем, таких как UNIX
или Windows
2000, и программного обеспечения Web-сервера
также имеет прямое отношение к
производительности; аналогично и
безопасность.

Начиная
с Apache
и заканчивая Zeus,
все программные платформы Web-серверов
обрабатывают базовые транзакции HTTP,
однако все они стремят­ся к тому, чтобы
обеспечить нечто большее, чем просто
элементарные сред­ства обслуживания
файлов. Большинство платформ Web-серверов
преду­сматривают базовые службы
обеспечения безопасности и аутентификации,
средства регистрации и программирования,
со­средоточимся лишь на аспектах,
связанных с программированием сайтов.

CGI

Относящиеся
к старейшей из технологий программирования,
работающих на стороне сервера, программы
CGI
(Common
Gateway
Interface,
общий шлюзовой интерфейс) могут
создаваться практически на любом языке
про­граммирования, хотя с приложениями
CGI,
как правило, ассоциируется язык Perl.
CGI
не является ни языком, ни программой; в
сущности, в отли­чие от других сред
программирования на стороне сервера,
которые опреде­ляют язык и стиль, это
— лишь способ создания программы. Как
показано на рис. 3.13, CGI
определяет базовые методы ввода и выхода
для программ на стороне сервера,
запускаемых Web-сервером.
Хотя некоторыми эта тех­нология
расценивается как медленная и небезопасная,
при условии пра­вильного понимания
и применения CGI
годится для многих проектов, свя­занных
с Web-разработкой.

Рисунок
8.1. Обзор CGI

8.2. Сценарии на стороне сервера

Технологии
создания сценариев на стороне сервера,
такие как Active
Server
Pages
(ASP)
от Microsoft
или ColdFusion
от Macromedia,
позволяют с легко­стью создавать
динамические страницы. Все языки
подготовки сценариев на стороне сервера,
включая распространенные ASP,
ColdFusion,
JSP
и PHP,
действуют довольно схожим образом.
Принцип заключается в том, что на сто­роне
сервера исполняются сценарные шаблоны,
содержащие сочетание HTML
и языка сценариев, и в результате
получается конечная Web-страница.
Обычно запросы на страницы перехватываются
неким механизмом на стороне сервера, и
когда встречаются файлы с определенными
расширениями — на­пример, asp,
cfm,
jsp,
php
или shtml,
элементы сценария на странице замеща­ются
конечной .

Языки сценариев
на стороне сервера часто применяются
для создания ди­намических страниц
из баз данных, персонализации содержимого
для поль­зователей или генерирования
на страницах компонентов, годных для
по­вторного использования. Синтаксис
каждого языка индивидуален, и многие
разработчики несколько фанатично
относятся к превосходствам одного
язы­ка над другим, однако суть дела в
том, что ни один из них не обладает
дос­таточной масштабируемостью в
условиях крайне высокообъемных сайтов.
Для таких сайтов обычно необходимы
серверные программы программного
интерфейса приложения

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

Аннотация: В данной лекции проводится краткое знакомство с одним из наиболее мощных языков программирования на стороне сервера — PHP, а также описаны способы его использования с Flash.

Внимание! Для работы с этой лекцией необходимы учебные файлы, которые Вы можете загрузить здесь.

Сегодняшний мир переполнен сокращениями. Вспомните такие аббревиатуры, как HTML, XML, HTTP, не забудьте и про Flash MX. Я хочу представить вам еще одно сокращение, о котором пойдет речь в данной лекции. PHP означает Hypertext Pre-Processor, это один из наиболее мощных языков сценариев серверной части. Примите это к сведению как веб-разработчик.

В этой лекции мы начнем с того, что представляет собой PHP, и немного поговорим о его истории.

История 101

Язык PHP был создан в конце 1994 года, когда Rasmus Lerdorf объединил набор сценариев Perl для сохранения записи посетителей его сетевого резюме. Эти сценарии заинтересовали посетителей его сайта, и в 1995 году они были опубликованы под названием «Personal Home Page Tools«.

Использование PHP быстро распространялось, так же как и количество разработчиков, занимающихся проектами PHP. На момент написания этой книги последней версией PHP является PHP 4, которая имеет доступ к большому числу дополнительных средств, некоторые из которых даже реализуют динамическое создание SWF-файлов, что называется, «с нуля».

Есть несколько моментов, которые необходимо иметь в виду при рассмотрении «движка» PHP (программа, непосредственно выполняющая сценарии PHP по команде веб-сервера).

  • Этот продукт доступен бесплатно, в т.ч. для использования в коммерческих целях.
  • Он является объектом Open Source. Это означает, что код доступен полностью и бесплатно и продукт постоянно развивается и совершенствуется разработчиками, сообщающимися друг с другом через интернет.
  • Существует множество сайтов, предлагающих бесплатные сценарии, от досок объявлений на базе HTML и программ поиска до сложных программ Flash.
  • Этот продукт доступен почти для любой платформы, включая Windows и ОС на базе Unix (например, Mac OSX).

Свежую информацию о PHP можно найти на сайтах www.php.net и www.zend.com.

Два сервера Вероны

Прежде чем приступать к работе с PHP, нужно познакомится с тем, что такое сценарий на стороне сервера и когда он должен использоваться. В этом параграфе я отвечу на поставленные вопросы и расскажу о том, как все «навороченные» сайты находят путь на ваш веб-браузер.

Ниже приведено определение сценария на стороне сервера.

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

Сценарий на стороне сервера позволяет выполнять некоторые процедуры на сервере перед возвратом веб-документа в браузер. Это может быть все, что угодно, начиная с управления файлами данных и заканчивая доступом к базе данных и динамической генерацией содержимого.

В стандартной настройке клиент-сервер клиентская программа (обычно это веб-браузер) открывает соединение с сервером и запрашивает файл. Сервер после этого возвращает файл клиентской части и соединение закрывается. Этот тип соединения используется при запросе, к примеру, HTML-файлов.

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

Чтобы вам было понятнее, рассмотрим простой пример. Я уверен, что вы уже более чем знакомы с различными поисковыми системами интернета. Я предпочитаю систему www.google.com, и если вы перейдете на этот сайт и выполните поиск по строке «Macromedia Flash«, вы будете перенаправлены на список соответствующих сайтов. В данный момент результаты поиска нам не интересны. Вместо этого следует обратить внимание на адрес URL в адресной строке вашего браузера. Он будет выглядеть примерно так.

http://www.google/search?hl=en&q=Macromedia+Flash

Этот адрес можно разбить на две части. Первая из них означает страницу, которая нам нужна, в данном случае, это поисковая страница Google.http://www.google.com/search

Эта страница и есть сценарий на стороне сервера, созданный для поиска в бесчисленном множестве веб-сайтов любого текста, удовлетворяющего отдельным словам, которые мы только что указали. Слова и выбранный язык прилагаются к URL в виде строки запроса следующим образом.

Здесь мы имеем дело с двумя переменными hl и q, устанавливаемыми на значения en и Macromedia+Flash, соответственно. Первая из них указывает язык поиска, вторая является критерием поиска или запросом и передается сценарию на стороне сервера или программе, используемой Google для поиска в базах данных. В данном случае это не сценарий PHP, однако важно понимать, что это мог быть именно PHP. Итак, поисковая система Google просто сопоставляет два источника информации — введенные пользователем данные и базу данных Google — после чего результаты передаются клиенту в виде HTML-страницы.

Самым замечательным является то, что сценарии на стороне сервера позволяют динамически создавать веб-содержимое. Можно изменять и адаптировать содержимое для определенного времени дня, для учета пользовательских предпочтений, для автоматического отображения списка последних новостей, для обновления сайтов. Все это можно проделывать без редактирования вручную указанных объектов.

Более того, с помощью сценариев на стороне сервера можно работать не только со страницами HTML — можно также создавать сценарии, возвращающие данные клиентам Flash, что значительно расширяет наши возможности. Этому и посвящена данная лекция.

Инсталляция PHP

Для работы с этой лекцией вам понадобится доступ к PHP веб-серверу. Если у вас есть свой собственный сервер, то вам нужно загрузить соответствующие файлы установки с сайта www.php.net, где также можно найти подробное руководство по установке. Имейте в виду, что для загрузки доступно несколько различных пакетов PHP с различными уровнями функциональности, однако пусть это вас не смущает — наиболее сокращенная версия как раз подойдет для работы в этой лекции.

Если у вас нет своего собственного сервера или вы не знаете, как превратить в сервер ваш собственный компьютер, вам нужно будет узнать в службе технической поддержки или у владельца компьютера, поддерживает ли он PHP и, если это не так, попробуйте уговорить их установить для вас эту поддержку!

Если у вас нет сервера, вы можете загрузить сервер apache с сайта www.apache.org.

From Wikipedia, the free encyclopedia

Languages used in server side scripting.

Server-side scripting is a technique used in web development which involves employing scripts on a web server which produces a response customized for each user’s (client’s) request to the website. The alternative is for the web server itself to deliver a static web page. Scripts can be written in any of a number of server-side scripting languages that are available (see below). Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.

Server-side scripting is often used to provide a customized interface for the user. These scripts may assemble client characteristics for use in customizing the response based on those characteristics, the user’s requirements, access rights, etc. Server-side scripting also enables the website owner to hide the source code that generates the interface, whereas, with client-side scripting, the user has access to all the code received by the client. A downside to the use of server-side scripting is that the client needs to make further requests over the network to the server in order to show new information to the user via the web browser. These requests can slow down the experience for the user, place more load on the server, and prevent the use of the application when the user is disconnected from the server.

When the server serves data in a commonly used manner, for example, according to the HTTP or FTP protocols, users may have their choice of a number of client programs (most modern web browsers can request and receive data using both of those protocols). In the case of more specialized applications, programmers may write their own server, client, and communications protocol, that can only be used with one another.

Programs that run on a user’s local computer without ever sending or receiving data over a network are not considered clients, and so the operations of such programs would not be considered client-side operations.

History[edit]

Netscape introduced an implementation of JavaScript for server-side scripting with Netscape Enterprise Server, first released in December, 1994 (soon after releasing JavaScript for browsers).[1][2]

Server-side scripting was later used in early 1995 by Fred DuFrense while developing the first website for Boston, MA television station WCVB. The technology is described in US patent 5835712. The patent was issued in 1998 and is now owned by Open Invention Network (OIN). In 2010 OIN named Fred DuFresne a «Distinguished Inventor» for his work on server-side scripting.

Explanation[edit]

In the earlier days of the web, server-side scripting was almost exclusively performed by using a combination of C programs, Perl scripts, and shell scripts using the Common Gateway Interface (CGI). Those scripts were executed by the operating system, and the results were served back by the webserver. Many modern web servers can directly execute on-line scripting languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via extension modules (e.g. mod_perl or mod_php) to the webserver. For example, WebDNA includes its own embedded database system. Either form of scripting (i.e., CGI or direct execution) can be used to build up complex multi-page sites, but direct execution usually results in less overhead because of the lower number of calls to external interpreters.

Dynamic websites sometimes use custom web application servers, such as Glassfish, Plack and Python’s «Base HTTP Server» library, although some may not consider this to be server-side scripting. When using dynamic web-based scripting techniques, developers must have a keen understanding of the logical, temporal, and physical separation between the client and the server. For a user’s action to trigger the execution of server-side code, for example, a developer working with classic ASP must explicitly cause the user’s browser to make a request back to the webserver.

Server-side scripts are completely processed by the servers instead of clients. When clients request a page containing server-side scripts, the application server processes the scripts and returns an HTML page to the client.

Server-side rendering[edit]

In the beginning of the web content was generated purely on the back end. After the big adoption of front end single-page applications, a new approach was introduced to generate the HTML using the client application, but on the back end. Examples of frameworks that use SSR are Next.js, Nuxt.js and Nest.js. They use React.js, Vue.js, and Angular, respectively, to generate the content of the server.

Server-side generation[edit]

Another similar to SSR technique of generating content for a website is using Server-side generation. This technique use application that create static html pages and then those files are send to the server. File generation can happen on completely different computer for example using continuous delivery. Example of SSG tools are Jekyll, Gatsby or Eleventy. Those sites are often hosted on Netlify or GitHub pages. GitHub also supports Jekyll projects where it automatically build the site when changes are added to git.

Languages[edit]

There are a number of server-side scripting languages available, including:

  • ActiveVFP (*.avfp)
  • ASP (*.asp)
  • ASP.NET Web Forms (*.aspx)
  • ASP.NET Web Pages (*.cshtml, *.vbhtml)
  • ColdFusion Markup Language (*.cfm)
  • Go (*.go)
  • Google Apps Script (*.gs)
  • Hack (*.php)
  • Haskell (*.hs) (example: Yesod)
  • Java (*.jsp, *.do) via JavaServer Pages
  • JavaScript using Server-side JavaScript (*.ssjs, *.js) (example: Node.js)
  • Lasso (*.lasso)
  • Lua (*.lp *.op *.lua)
  • Parser (*.p)
  • Perl via the CGI.pm module (*.cgi, *.ipl, *.pl)
  • PHP (*.php, *.php3, *.php4, *.phtml)
  • Python (*.py) (examples: Pyramid, Flask, Django)
  • R (*.rhtml)
  • Ruby (*.rb, *.rbw) (example: Ruby on Rails)
  • Tcl (*.tcl)
  • WebDNA (*.dna,*.tpl)
  • Progress WebSpeed (*.r,*.w)

See also[edit]

  • Client-side scripting
  • Content management system (CMS)
  • Edge Side Includes
  • JSP
  • Node.js
  • Next.js
  • Outline of web design and web development
  • Perl/Plack
  • PHP
  • Server Side Includes (SSI)
  • Web development

References[edit]

  1. ^ «Server-Side JavaScript Guide». Netscape Communications Corporation. 1998. Retrieved 2012-04-25.
  2. ^ Mike Morgan (1996). «Using Netscape™ LiveWire™, Special Edition». Que.

External links[edit]

  • Server-side scripting at Curlie;

From Wikipedia, the free encyclopedia

Languages used in server side scripting.

Server-side scripting is a technique used in web development which involves employing scripts on a web server which produces a response customized for each user’s (client’s) request to the website. The alternative is for the web server itself to deliver a static web page. Scripts can be written in any of a number of server-side scripting languages that are available (see below). Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.

Server-side scripting is often used to provide a customized interface for the user. These scripts may assemble client characteristics for use in customizing the response based on those characteristics, the user’s requirements, access rights, etc. Server-side scripting also enables the website owner to hide the source code that generates the interface, whereas, with client-side scripting, the user has access to all the code received by the client. A downside to the use of server-side scripting is that the client needs to make further requests over the network to the server in order to show new information to the user via the web browser. These requests can slow down the experience for the user, place more load on the server, and prevent the use of the application when the user is disconnected from the server.

When the server serves data in a commonly used manner, for example, according to the HTTP or FTP protocols, users may have their choice of a number of client programs (most modern web browsers can request and receive data using both of those protocols). In the case of more specialized applications, programmers may write their own server, client, and communications protocol, that can only be used with one another.

Programs that run on a user’s local computer without ever sending or receiving data over a network are not considered clients, and so the operations of such programs would not be considered client-side operations.

History[edit]

Netscape introduced an implementation of JavaScript for server-side scripting with Netscape Enterprise Server, first released in December, 1994 (soon after releasing JavaScript for browsers).[1][2]

Server-side scripting was later used in early 1995 by Fred DuFrense while developing the first website for Boston, MA television station WCVB. The technology is described in US patent 5835712. The patent was issued in 1998 and is now owned by Open Invention Network (OIN). In 2010 OIN named Fred DuFresne a «Distinguished Inventor» for his work on server-side scripting.

Explanation[edit]

In the earlier days of the web, server-side scripting was almost exclusively performed by using a combination of C programs, Perl scripts, and shell scripts using the Common Gateway Interface (CGI). Those scripts were executed by the operating system, and the results were served back by the webserver. Many modern web servers can directly execute on-line scripting languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via extension modules (e.g. mod_perl or mod_php) to the webserver. For example, WebDNA includes its own embedded database system. Either form of scripting (i.e., CGI or direct execution) can be used to build up complex multi-page sites, but direct execution usually results in less overhead because of the lower number of calls to external interpreters.

Dynamic websites sometimes use custom web application servers, such as Glassfish, Plack and Python’s «Base HTTP Server» library, although some may not consider this to be server-side scripting. When using dynamic web-based scripting techniques, developers must have a keen understanding of the logical, temporal, and physical separation between the client and the server. For a user’s action to trigger the execution of server-side code, for example, a developer working with classic ASP must explicitly cause the user’s browser to make a request back to the webserver.

Server-side scripts are completely processed by the servers instead of clients. When clients request a page containing server-side scripts, the application server processes the scripts and returns an HTML page to the client.

Server-side rendering[edit]

In the beginning of the web content was generated purely on the back end. After the big adoption of front end single-page applications, a new approach was introduced to generate the HTML using the client application, but on the back end. Examples of frameworks that use SSR are Next.js, Nuxt.js and Nest.js. They use React.js, Vue.js, and Angular, respectively, to generate the content of the server.

Server-side generation[edit]

Another similar to SSR technique of generating content for a website is using Server-side generation. This technique use application that create static html pages and then those files are send to the server. File generation can happen on completely different computer for example using continuous delivery. Example of SSG tools are Jekyll, Gatsby or Eleventy. Those sites are often hosted on Netlify or GitHub pages. GitHub also supports Jekyll projects where it automatically build the site when changes are added to git.

Languages[edit]

There are a number of server-side scripting languages available, including:

  • ActiveVFP (*.avfp)
  • ASP (*.asp)
  • ASP.NET Web Forms (*.aspx)
  • ASP.NET Web Pages (*.cshtml, *.vbhtml)
  • ColdFusion Markup Language (*.cfm)
  • Go (*.go)
  • Google Apps Script (*.gs)
  • Hack (*.php)
  • Haskell (*.hs) (example: Yesod)
  • Java (*.jsp, *.do) via JavaServer Pages
  • JavaScript using Server-side JavaScript (*.ssjs, *.js) (example: Node.js)
  • Lasso (*.lasso)
  • Lua (*.lp *.op *.lua)
  • Parser (*.p)
  • Perl via the CGI.pm module (*.cgi, *.ipl, *.pl)
  • PHP (*.php, *.php3, *.php4, *.phtml)
  • Python (*.py) (examples: Pyramid, Flask, Django)
  • R (*.rhtml)
  • Ruby (*.rb, *.rbw) (example: Ruby on Rails)
  • Tcl (*.tcl)
  • WebDNA (*.dna,*.tpl)
  • Progress WebSpeed (*.r,*.w)

See also[edit]

  • Client-side scripting
  • Content management system (CMS)
  • Edge Side Includes
  • JSP
  • Node.js
  • Next.js
  • Outline of web design and web development
  • Perl/Plack
  • PHP
  • Server Side Includes (SSI)
  • Web development

References[edit]

  1. ^ «Server-Side JavaScript Guide». Netscape Communications Corporation. 1998. Retrieved 2012-04-25.
  2. ^ Mike Morgan (1996). «Using Netscape™ LiveWire™, Special Edition». Que.

External links[edit]

  • Server-side scripting at Curlie;

читайте также по теме: Управляемый сайт

Приведённый здесь текст был написан мной на заре моего знакомства с программированием для web, когда я постигал азы CGI-интерфейса.
Можеть быть, для вас будет более интересен другой материал — «Управляемый сайт».

Для того чтобы создать свою страничку в глобальной сети сейчас достаточно приложить совсем немного собственных усилий, но чтобы «родной уголок» не выглядел набором «мертвых» статических HTML-документов, приходится использовать различные «динамические» технологии.
Часть из них позволяет «оживить» HTML-документ в окне браузера пользователя (Gif89a, DHTML, JavaScript, VBScript, Flash, Java).
Другая группа позволяет разработать «думающий» сайт, используя возможности сервера (CGI-приложения, SSI, PHP, ASP, Perl).
Рассмотрим на небольшом примере возможности динамической генерации HTML-документов на стороне сервера с помощью сценариев PHP и ASP.

Существует много способов для создания динамических HTML-страниц, но страницы, формируемые с помощью серверных сценариев, имеют несколько неоспоримых преимуществ.
По сравнению, например, со сценариями JavaScript или VBScript, которые не могут сохранять свое состояние (кроме как в «ключиках» клиентского браузера), серверные сценарии могут использовать ресурсы самого сервера для сохранения своего состояния или других данных.
Кроме того, так как сценарии выполняются на стороне сервера, их не надо передавать по сети, и скорость выполнения таких сценариев не зависит от возможностей клиентской машины.

Гостевая книга

Типичным примером взаимодействия личного сетевого HTTP-узла является функционирование так называемой гостевой книги.
Попробуем на этом примере рассмотреть и сравнить два вида сценариев PHP и ASP, применяемых на популярных web-серверах Apache и IIS соответственно.

Первая задача, которую необходимо решить, как передать и сохранить на сервере текст сообщения, посылаемый посетителем сетевого узла.
В таких случаях вполне подходит CGI (Common Gateway Interface) механизм передачи параметров от пользователя к серверу.
По спецификации CGI чтобы передать параметры приложению на сервере, надо либо разместить их в строке адреса URL (метод get), либо в самом HTTP-заголовке в виде переменных окружения (метод post).
То есть, если в HTML-документе имеется форма с текстовыми полями ввода, то после нажатия на кнопку отправки запроса имеем:

Метод get Метод post
HTML-документ
 action="myscript" method="get">
   type="text" name="Var1" value="Alex">
   type="text" name="Var2" value="Hello">
  ...
 action="myscript" method="post">
   type="text" name="Var1" value="Alex">
   type="text" name="Var2" value="Hello">
  ...
приложение на стороне сервера
Сформированная строка адреса запроса:
myscript?Var1=Alex&Var2=Hello
Командная строка вызова CGI-приложения:
myscript Var1=Alex Var2=Hello
Таким образом, приложение myscript получит при вызове два параметра в командной строке Var1=Alex и Var2=Hello, из которых и сможет получить необходимые значения полей ввода Var1 и Var2.
Сформированная строка адреса запроса:
myscript
Переменные окружения в HTTP-заголовке
Var1=Alex
Var2=Hello

Таким образом, для доступа к значениям полей ввода приложению myscript необходимо выбрать значения у переменных окружения Var1 и Var2.

Отсюда сразу видно, что для передачи длинных строк более удобен метод post, так как ограничения на длину строки адреса запроса не актуальны.
Зато метод get прост для передачи параметров при простом переходе по ссылке в HTML-документе и не требует наличия в документе формы с кнопкой отправки запроса.

Итак, в гостевой книге сообщение может иметь достаточно большую длину, поэтому будем использовать метод post.
Допустим, у нас имеется следующая форма:

Допустим, PHP сценарий добавления новой записи называется addsign.php, а ASP — addsign.asp.
Чтобы сообщения сохранялись на сервере, можно воспользоваться возможностью управления файлами на сервере.
Так, для каждого сообщения можно создавать отдельный текстовый файл, содержащий его тело.
Для удобства перечисления можно использовать числовое имя файла, а общее количество сообщений хранить в отдельном файле.
Перечислим необходимые функции и методы соответственно:

PHP ASP
Открытие текстового файла
integer fopen ( string Filename, string Ftatus )
Возвращает номер дескриптора открытого файла
Filename — имя открываемого файла
Status — вариант доступа к файлу, может принимать одно из следующих значений:
«r» — открыть для чтения
«w» — открыть для записи
«w+» — открыть для чтения и записи
Для начала надо создать объект файловой системы с помощью функции:
object CreateObject ( «Scripting.FileSystemObject» )
Возвращает объект файловой системы
Далее можно получить объект текстового файла с помощью метода объекта файловой системы:
object filesystem.OpenTextFile ( str Filename, int Status )
Возвращает объект, инкапсулирующий работу с текстовым файлом.
Filename — имя открываемого файла
Status — вариант доступа к файлу, может принимать одно из следующих значений:
1 — открыть для чтения
2 — открыть для записи
8 — открыть для чтения и записи
Чтение строки из текстового файла
string fgets ( integer FileDescriptor, integer StringLength );
Возвращает строку длины StringLength, считанную из открытого файла с дескриптором FileDescriptor.
str file.ReadLine
Возвращает строку, считанную из ассоциированного с объектом file открытого файла.
Запись строки в текстовый файл
fwrite ( integer FileDescriptor, string String, integer StringLength );
Записывает в открытый с дескриптором FileDescriptor файл StringLength символов строки String.
file.WriteLine str String
Записывает строку String в открытый файл, ассоциированный с объектом file.
Закрытие файла
fclose ( integer FileDescriptor );
Закрывает открытый с дескриптором FileDescriptor файл.
file.Close
Закрывает ассоциированный с объектом file открытый файл.
Доступ к переменным окружения
string getenv ( string EnvVariable );
Возвращает содержимое EnvVariable переменной окружения.
При запуске сценария переменные окружения автоматически отображаются в одноименные внутренние переменные PHP сценария.
str Request.ServerVariables ( str EnvVariable )
Возвращает содержимое EnvVariable переменной окружения.
Доступ к параметрам командной строки
При запуске сценария парметры командной строки автоматически отображаются в одноименные внутренние переменные PHP сценария. str Request.QueryString ( str ParamVariable )
Возвращает содержимое ParamVariable параметра командной строки.

Теперь код сценариев добавления новой записи. Будем считать, что через 1000 обращений новые сообщения начнут перезаписываться поверх старых, чтобы не переполнять дисковое пространство:

addsign.php addsign.asp
Получение значения переменных окружения
  set file = fs.OpenTextFile ("msgqty.txt", 2)
  file.WriteLine ( MsgQty )
  file.Close
%>;

А теперь код сценариев просмотра записей гостевой книги:

guestbook.php guestbook.asp
Получение текущего числа сообщений из файла «msgqty.txt»
  for i = MsgQty to 1 step -1
    ' Read messages
    FName = "msg" + CStr(i) + ".txt"
    set file = fs.OpenTextFile (FName, 1)
    str = file.ReadLine
    while not file.AtEndOfStream
      str = file.ReadLine
      Response.Write str
    wend
    Response.Write "
"
next %>

Очевидно, что при большом количестве сообщений пользователю придется долго ждать окончания загрузки страницы, поэтому имеет смысл гостевую книгу «разбить на страницы».
Для этого хорошо подходит передача параметров методом get, так как можно с помощью обычной гиперссылки передавать номер сообщения, с которого надо начать показ.
Например, до показа сообщений вывести строчку вида Следующие сообщения..., а в самом начале анализировать строку запроса на присутствие параметра start, и если он задан выдать соответствующую «порцию» сообщений.

Остальные модернизации «гостевой книги» ограничиваются только вашей фантазией. Удачи!

30 июля 2000—11 августа 2000

Максим Проскурня

Понравилась статья? Поделить с друзьями:
  • Сценарии лекционного занятия
  • Сценарии иностранных фильмов
  • Сценарии голливудских фильмов на русском языке
  • Сценарии осенних баллов
  • Сценарии на смешные сценки квн