- Php oracle client windows
- Введение
- Установка PHP
- Oracle и PHP — это очень просто
- Введение
- Установка PHP
- Правка файла конфигурации PHP
- Перезапуск Apache и проверка
- Некоторые возможности PHP
- Работа с Oracle
- Oracle, да не только
- 9 PHP Client
- 9.1 Before You Begin
- 9.2 Integrating with an Inline Service Using the Oracle RTD PHP Client
- 9.2.1 Deploying the PHP Client Example
- 9.2.2 Setting up the Oracle RTD PHP Client .ini File
- 9.2.3 Editing the Nusoap Path Library Location
- 9.2.4 Creating the Oracle RTD PHP Client
- 9.2.5 Creating the Request
- 9.2.6 Examining the Response
- 9.2.7 Closing the Loop
Php oracle client windows
Владимир Пржиялковский , преподаватель технологий Oracle
. Он бежит себе в волнах
На раздутых парусах.
PHP – простое в употреблении, легкое и бесплатное средство для динамического построения страниц HTML на сервере, перед передачей клиенту в браузер. PHP умеет обращаться в СУБД Oracle, и это делает его хорошим кандидатом для разработки приложений web на основе Oracle малой и средней сложности.
Введение
СУБД Oracle, когда против желания фирмы-изготовителя, а когда согласно – в зависимости от направления политических ветров в конкретные периоды времени, – никогда, кроме начального периода своего существования, не была полностью закрытой системой. Например, с момента возникновения движения свободного ПО, разработки, ведущиеся открытым образом («открытыми текстами»), все время держали эту СУБД в зоне своих интересов. Когда некоторые представители такого ПО стали достаточно зрелыми, фирма Oracle, подобно другим крупным фирмам, «легализовала» связь своей СУБД с ними: ОС Linux входит в число стратегических платформ для Oracle, web-сервер Apache входит в состав штатной поставки; там же можно обнаружить следы Perl и Tcl, нашедших себе место во внутреннх процессах установки (OUI) и администрирования (OEM). Эти средства помогают организовать взаимодействие с Oracle вместо средств собственной разработки (например, Developer) или в дополнение к ним.
PHP принадлежит к числу средств открытого ПО, не самых популярных, но вполне состоявшихся, востребованность которых непрерывно растет (см. http://www.php.net/usage.php). PHP позволяет динамически формировать страницы HTML на сервере web. В этом качестве он занимает нишу, общую с EmbPerl, Mason, Aquaruim (все – свободное ПО) и сервлетами (например, с JavaServer Pages). Сервером web может быть Apache, IIS или же еще несколько разновидностей. Здесь нам важно, что PHP умеет обращаться к СУБД Oracle и что это легкая и простая система.
Установка PHP
Дальнейшие примеры будут приведены для связки Windows + Apache. Удобнее всего использовать версию Apache со штатного установочного комплекта СУБД Oracle (в версии Oracle 10.1 – на Companion CD). Дежурное напоминание: для промыщленного использования сервера web лучше все же взять последнюю версию Apache из сети, так как она более функциональна, надежна и защищена.
Версию PHP можно скачать с узла http://www.php.net/. Там же имеются документация, учебные материалы, форумы и ссылки на ресурсы, в числе которых есть русскоязычные. К примеру, для Windows можно скачать файл php-4.3.6-Win32.zip. Его нужно поместить в каталог, например c:\php, и разархивировать. Далее можно следовать инструкциям в install.txt, однако само ПО PHP уже установлено. В Unix еще потребуется построить библиотеки программой make.
Правка файла конфигурации PHP
Найдите файл php.ini. Скорее всего он в каталоге c:\WINNT. Найдите параметр extension_dir и проставьте
Снимите комментарии со строк
;extension=php_oci8.dll
;extension=php_oracle.dll
;extension=php_dbase.dll
Последний параметр требуется раскомментарить только если вы намерены проиграть следующий далее пример с записью данных в формате dbf.
Правка файла конфигурации Apache
Найдите файл httpd.conf. Скорее всего он в каталоге %ORACLE_HOME%\Apache\Apache\conf. Добавьте строки:
LoadModule php4_module C:/php/php-4.3.6-Win32/sapi/php4apache.dll
AddModule mod_php4.c
AddType application/x-httpd-php .php
Последний параметр уже присутствует в виде комментария, и для него достаточно просто знак комментария снять.
Копирование файлов динамических модулей
В соответствии с указанным в php.ini значением параметра extension_dir скопируем файлы:
c:
cd \php\php-4.3.0-Win32
move php4ts.dll sapi
move extensions\php_oci8.dll sapi
move extensions\php_oracle.dll sapi
Перезапуск Apache и проверка
Осталось перезапустить Apache. Это можно сделать либо с помощью меню Start, либо через останов и запуск службы Windows. Если все проделано правильно, при запуске не будет ошибок.
Oracle и PHP — это очень просто
Введение
СУБД Oracle, когда против желания фирмы-изготовителя, а когда согласно – в зависимости от направления политических ветров в конкретные периоды времени, – никогда, кроме начального периода своего существования, не была полностью закрытой системой. Например, с момента возникновения движения свободного ПО, разработки, ведущиеся открытым образом («открытыми текстами»), все время держали эту СУБД в зоне своих интересов. Когда некоторые представители такого ПО стали достаточно зрелыми, фирма Oracle, подобно другим крупным фирмам, «легализовала» связь своей СУБД с ними: ОС Linux входит в число стратегических платформ для Oracle, web-сервер Apache входит в состав штатной поставки; там же можно обнаружить следы Perl и Tcl, нашедших себе место во внутреннх процессах установки (OUI) и администрирования (OEM). Эти средства помогают организовать взаимодействие с Oracle вместо средств собственной разработки (например, Developer) или в дополнение к ним.
PHP принадлежит к числу средств открытого ПО, не самых популярных, но вполне состоявшихся, востребованность которых непрерывно растет (см. http://www.php.net/usage.php ). PHP позволяет динамически формировать страницы HTML на сервере web. В этом качестве он занимает нишу, общую с EmbPerl, Mason, Aquaruim (все – свободное ПО) и сервлетами (например, с JavaServer Pages). Сервером web может быть Apache, IIS или же еще несколько разновидностей. Здесь нам важно, что PHP умеет обращаться к СУБД Oracle и что это легкая и простая система.
Установка PHP
Дальнейшие примеры будут приведены для связки Windows + Apache. Удобнее всего использовать версию Apache со штатного установочного комплекта СУБД Oracle (в версии Oracle 10.1 – на Companion CD). Дежурное напоминание: для промыщленного использования сервера web лучше все же взять последнюю версию Apache из сети, так как она более функциональна, надежна и защищена.
Версию PHP можно скачать с узла http://www.php.net/. Там же имеются документация, учебные материалы, форумы и ссылки на ресурсы, в числе которых есть русскоязычные. К примеру, для Windows можно скачать файл php-4.3.6-Win32.zip. Его нужно поместить в каталог, например c:php, и разархивировать. Далее можно следовать инструкциям в install.txt, однако само ПО PHP уже установлено. В Unix еще потребуется построить библиотеки программой make.
Правка файла конфигурации PHP
Найдите файл php.ini. Скорее всего он в каталоге c:WINNT. Найдите параметр extension_dir и проставьте
Снимите комментарии со строк
Последний параметр требуется раскомментарить только если вы намерены проиграть следующий далее пример с записью данных в формате dbf.
Правка файла конфигурации Apache
Найдите файл httpd.conf. Скорее всего он в каталоге %ORACLE_HOME%ApacheApacheconf. Добавьте строки:
Последний параметр уже присутствует в виде комментария, и для него достаточно просто знак комментария снять.
Копирование файлов динамических модулей
В соответствии с указанным в php.ini значением параметра extension_dir скопируем файлы:
Перезапуск Apache и проверка
Осталось перезапустить Apache. Это можно сделать либо с помощью меню Start, либо через останов и запуск службы Windows. Если все проделано правильно, при запуске не будет ошибок.
Составим файл test.php:
Поместим файл в %ORACLE_HOME%ApacheApachehtdocs. Наберем в браузере адрес http://localhost:7778/test.php (в версии Oracle 8 номер порта или убрать, или указать 80).
Некоторые возможности PHP
PHP, конечно, не столь универсальный язык, как Java, используемая в JavaServer Pages, но достаточно богат. Описание его можно найти в книгах, например в http://www.ccas.ru/
prz/ORA/phppr.html, или на вышеуказанной официальной странице PHP в интернете. Вот некоторые особенности языка.
Вставки PHP в текст HTML можно оформлять не только как (см. выше), но и проще как (что не рекомендуется) или же как (что длиннее).
phpinfo() в примере выше – встроенная функция PHP. Регистр, которым набираются имена функций в PHP несущественен, а для переменных (предваряются знаком $, $currtime и $currtimestr в примере выше) наоборот, существенен.
Переменные могут быть типов целого, плавающего, строка, массив, объект и булевского. Возможно явное преобразование типов. Выражения и операторы похожи на используемые в C и Perl.
Набор функций достаточно широк и позволяет производить вычисления (в том числе с произвольной точностью), обращаться к файлам ОС и к различным базам данных, к сетевым ресурсам (например, по ftp) и к серверам LDAP, рисовать изображения и динамически выводить данные в формате pdf и многое другое. Вот несколько примеров функций, на вскидку:
— string crypt(string str, [, string salt]) – шифрование строки по алгоритму DES, наприме перед помещением ее в БД (для шифрования разными методами есть и другие функции)
— int syslog(int priority, string message) – посылка сообщения в журнал ОС
— int xml_parse(int parser, string data[, int is_final]) – синтаксический разбор документа XML
Посмотрим, как может выполняться обращение к данным в Oracle.
Работа с Oracle
Обращение с помощью PHP к данным в Oracle может осуществляться через CGI или через специальные функции. Первая возможность рискована с точки зрения безопасности и здесь не рассматривается.
Вторая, в свою очередь, реализуется двумя имеющимися библиотеками: php_oracle и php_oci8, из которых вторая считается более эффективной. Продемонстрировать ту и другую можно на примере файла employees.php:
Снова поместим файл в htdocs и обратимся по адресу http://localhost:7778/employees.php.
Этот пример для наглядности упрощен, а в жизни нужно будет больше уделить места обработке ошибок и структуризации кода.
Вот пример вставки записи в БД. Данные передаются через строку запроса HTTP. Это позволяет организовать в приложении содержательный диалог, подключив средства ввода форм HTML.
Подготовим файл insert.php:
Поместим файл в htdocs и обратимся по адресу http://localhost:7778/insert.php?empname=Вася&empno=1111. В SQL*Plus или предыдущей страницей PHP можно проверить результат. Обратите внимание на то, что в приведенном примере никак не обрабатывается (а) блокировка строк, возможно мешающая вставке и (б) возможный конфликт первичного ключа.
Oracle, да не только
Как говорилось выше, PHP имеет функции обращения к данным отнюдь не только в Oracle. Наличие этих функций дает возможным использования этого инструмента достаточно экзотично, например для переноса данных между Oracle и другими системами. Например, нередко стоит задача переноса из формата dbf в БД под управлением Oracle или наоборот. Вот как ее можно решить «на коленке». Обратите внимание, что перенос инициируется из окошка браузера, а выполняется целиком на узле web.
Составим файл dbase.php:
Поместим файл в htdocs и обратимся по адресу http://localhost:7778/dbase.php. В каталоге с: должен появиться файл fromoracle.dbf с данными, полученными из Oracle. Обратное преобразование можно проделать в качестве упражнения.
Таким же образом можно обращаться к mySQL, PostgreSQL, Sybase, SQL Server и другим системам управления данными и по ODBC.
9 PHP Client
This chapter explains how to integrate an Inline Service with the Oracle RTD PHP Client, using the CrossSell Inline Service as an example.
A convenient way to integrate a Web application with a deployed Inline Service is to use the PHP client integration classes. PHP allows you to generate interactive Web pages. The PHP classes provided offer functionality similar to the Java Smart Client discussed in a previous chapter.
This chapter contains the following topics:
9.1 Before You Begin
You must perform the following tasks first before you can work with the PHP Client example:
Install a Java Development Kit (JDK), with the JAVA_HOME environment variable set to its location. To obtain a JDK, go to the site:
For more details about supported versions, see the documents referenced in Section 6.4, «System Requirements and Certification.»
Install the Oracle RTD files and deploy Oracle RTD to an application server. See Oracle Fusion Middleware Installation Guide for Oracle Business Intelligence for full information.
The PHP Client example works with the sample CrossSell Inline Service. Because of this, you must first populate the Oracle RTD Database with the CrossSell example data, then deploy the CrossSell Inline Service using Decision Studio. For details, see the section «Populating the CrossSell Example Data» in Oracle Fusion Middleware Administrator’s Guide for Oracle Real-Time Decisions and Part III, «Decision Studio Reference» for information about deploying Inline Services.
Install and configure an environment suitable for evaluating PHP 5.2 scripts, such as Apache with mod_php. Please consult the documents referenced in Section 6.4, «System Requirements and Certification» for supported versions and operating systems.
Install either PHP Soap or NuSoap (release 0.7.3) from SourceForge.
9.2 Integrating with an Inline Service Using the Oracle RTD PHP Client
In general, integration using the Oracle RTD PHP Client includes the following steps:
Prepare an Oracle RTD PHP Client .ini file.
Prepare Client objects.
Create a request that identifies the following:
The Integration Point to connect to
The parameters to identify the session
Any other information the Integration Point needs to determine an outcome
Use Oracle RTD PHP method syntax to create requests for Informants.
Use Oracle RTD PHP method syntax to parse responses from Advisors.
Close the connection.
Two working examples of using the PHP Client may be found at RTD_HOME \client\Client Examples\PHP Client Example :
example_nusoap.php demonstrates the use of the Oracle RTD PHP Client with NuSoap
example.php implements the same functionality but uses PHP Soap
The rest of this section consists of the following topics:
9.2.1 Deploying the PHP Client Example
For this example, the CrossSell Inline Service is exercised by a simple PHP page to demonstrate how to use the PHP Client.You need to deploy the PHP Client example to your application server, as described in the following section.
To deploy the PHP Client example to Apache:
Place the Oracle RTD PHP Client library:
RTD_HOME \client\Client Examples\PHP Client Example\rtd
either into a location on your PHP include path or to the web site pages folder, such as htdocs for the Apache HTTP server.
This rtd folder should contain the following files:
As part of your setup, you must ensure that the .ini file that you use is appropriate for your environment. For more information, see Section 9.2.2, «Setting up the Oracle RTD PHP Client .ini File.»
Place the appropriate Oracle RTD PHP Client example — example.php for PHP Soap or example_nusoap.php for NuSoap — into a path from which your Apache server is configured to serve PHP scripts, for example, /home/www/example.php .
To access the application, open a Web browser and go to:
http:// apache_host:port /example.php (for PHP)
http:// apache_host:port /example_nusoap.php (for NuSoap)
Enter a customer ID (such as 5) and click OK.
The example is explained in more detail in the sections that follow.
9.2.2 Setting up the Oracle RTD PHP Client .ini File
The .ini files provided by Oracle RTD are the following:
rtd_client_conf.ini (for PHP Soap)
rtd_client_nusoap_conf.ini (for NuSoap)
The PHP client properties in these files are as follows:
wsdl — wsdl file location. Use with PHP Soap.
If the PHP Client library is in a location on your PHP include path, you can specify the wsdl location in either of the following ways:
You can provide a full path name, such as c:\php\includes\rtd\DecisionService.wsdl
If you have copied the DecisionService.wsdl file into the web site pages folder, such as htdocs for the Apache HTTP server, then you can provide a relative path name for the wsdl property. For example, rtd\DecisionService.wsdl .
clientClass — Client class name
appsCacheClass — Cache class name
appsCacheFile — temp file for default response
clientTimeout — Oracle RTD integration point invoke timeout in seconds. This is optional.
endpointUrl — url for the decision service
username — user name to connect to the server
password — password to connect to the server
Example of rtd_client_conf.ini
The following is an example of rtd_client_conf.ini :
Example of rtd_client_nusoap_conf.ini
The following is an example of rtd_client_nusoap_conf.ini :
Editing the .ini files
Oracle RTD provides Client example initialization files as a basis for your configuration. You must ensure that the settings in the files match your system. If necessary, edit the files so that they are correct for your configuration setup.
For example, if your Real-Time Decision Server server is not running on localhost or its listening port is not 8080, you must edit the appropriate .ini file before deploying the Oracle PHP Client example, as follows:
In RTD_HOME \client\Client Examples\PHP Client Example\rtd , open the appropriate file, rtd_client_conf.ini or rtd_client_nusoap_conf.ini, with a text editor.
Search for the entry:
Change the URL localhost:8080 to match the host and port of the Real-Time Decision Server that you are using.
How the Client Properties are Used
When a client application creates an Oracle RTD PHP Client, it passes a set of properties to an Oracle RTD PHP Client factory that represents the component’s endpoint configuration.
If no argument is given, the Client factory derives its settings by applying parse_ini_file to rtd_client_conf.ini .
The factory method uses the settings to connect to the server. When the Oracle RTD PHP Client has connected to the server, it downloads a more complete set of configuration information, such as the set of default responses that the client should use if it ever needs to run when the server is unavailable.
The detailed client configuration is saved in a local file, the Oracle RTD PHP Client configuration cache, and is updated automatically whenever the server’s configuration changes.
9.2.3 Editing the Nusoap Path Library Location
The Oracle RTD client library assumes that nusoap.php is located in a directory structure of the form
is among the PHP installation’s include directories.
However, nusoap files download into the directories lib and sample .
Users must do the following:
Copy the contents of the lib directory to
In rtd.client.nusoap.php , edit the following entry:
to reflect the actual nusoap library location.
The following include is used to support Oracle RTD integration with NuSoap:
9.2.4 Creating the Oracle RTD PHP Client
To create the Oracle RTD PHP Client, open the source file for the Example PHP script appropriate for your environment ( example.php for users of PHP Soap and example_nusoap.php for NuSoap users).
The following include is used to support Oracle RTD integration with NuSoap:
The following include is used to support Oracle RTD integration with PHP Soap:
example.php and example_nusoap.php demonstrate different ways of obtaining an instance of the Oracle RTD PHP Client.
A client may be obtained with settings given explicitly inline, as is shown by example.php :
In example_nusoap.php , the settings are parsed from a .ini file that has been placed in the same directory as the example PHP script, and may be found in RTD_HOME \client\Client Examples\PHP Client Example\rtd\rtd_client_nusoap_conf.ini :
9.2.5 Creating the Request
This line of code creates a Request object:
A request must be configured with the destination Inline Service:
The selection of an Inline Service may be further specialized with a Deployment State. If omitted then the Inline Service deployed in the highest State receives the Request (Production is higher than QA, which is higher than Development):
The details of a Request are specific to each Inline Service. In this example, the CallStart Informant requires a Session Key named customerId and an additional parameter named channel :
After populating the request, the client application calls the invoke method of the Client, sending the Request to the RTD Server:
9.2.6 Examining the Response
When an Advisor is invoked, a number of response items, also known as Choices, will be returned. Your application must be prepared to handle these items. See Section 6.2.3, «Determining the Response of an Advisor» for more information.
In the client PHP script, the selected Choices are accessible through the Response interface returned by the Client’s invoke method. This object provides access to an array of ResponseItem objects, each one corresponding to a Choice object selected by the Advisor’s Decision.
The Choice’s name may be accessed with the getId() method, and the Choice’s attributes are available through getAttributes() :
In the PHP example scripts, the response items are each printed to the web page in the order given by the RTD server:
9.2.7 Closing the Loop
Many Inline Services are designed to be self learning. In the CrossSell Inline Service, the OfferResponse Informant reports interest in a cross sell offer back to a Choice Event Model. For simplicity, this example registers an «Interested» Choice Event for the highest ranked Choice among the response items.
For more information about Choice Event models and Choices, see Section 6.2.4, «Identifying Event Responses to Oracle RTD.»
Finally, the session is closed by invoking the CallResolution Informant, which in the CrossSell example has been designed to terminate the session, freeing resources and triggering tasks to run that wait for the end of a session.