When using the OCI_CRED_EXT in php
if the ENV $ORACLE_SID is set the DB does not need to be specified explicitly and the connection will fail unless you provide a NULL DB value when creating the connection.
The $ORACLE_SID trumps the TNS name look up for the connection. So even a manual connection string in the DB parameter will fail.
So when the $ORACLE_SID Env is set a NULL passed instead of the DB name connects successfully.
Hope this saves some hair pulling when moving to %.3 and OS Authentications
oci_connect
(PHP 5, PECL oci8 >= 1.1.0)
oci_connect — Establishes a connection to the Oracle server
Descrierea
Returns a connection identifier needed for most other OCI calls.
Parametri
- username
-
The Oracle user name.
- password
-
The password for username .
- db
-
This optional parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora.
If the not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.
- charset
-
Utilizând Oracle server de versiune 9.2 sau ulterioară, puteţi să indicaţi charset în calitate de parametru, care va fi utilizat în noua conexiune. Dacă utilizaţi Oracle server < 9.2, acest parametru va fi ignorat şi în loc va fi utilizată variabila de mediu NLS_LANG.
- session_mode
-
This parameter is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Valorile întroarse
Returns a connection identifier or FALSE on error.
Exemple
Example #1 oci_connect() example
<?php
echo "<pre>";
$db = "";
$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_connect("scott", "tiger", $db);
function create_table($conn)
{
$stmt = oci_parse($conn, "create table scott.hallo (test varchar2(64))");
oci_execute($stmt);
echo $conn . " created table\n\n";
}
function drop_table($conn)
{
$stmt = oci_parse($conn, "drop table scott.hallo");
oci_execute($stmt);
echo $conn . " dropped table\n\n";
}
function insert_data($conn)
{
$stmt = oci_parse($conn, "insert into scott.hallo
values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
oci_execute($stmt, OCI_DEFAULT);
echo $conn . " inserted hallo\n\n";
}
function delete_data($conn)
{
$stmt = oci_parse($conn, "delete from scott.hallo");
oci_execute($stmt, OCI_DEFAULT);
echo $conn . " deleted hallo\n\n";
}
function commit($conn)
{
oci_commit($conn);
echo $conn . " committed\n\n";
}
function rollback($conn)
{
oci_rollback($conn);
echo $conn . " rollback\n\n";
}
function select_data($conn)
{
$stmt = oci_parse($conn, "select * from scott.hallo");
oci_execute($stmt, OCI_DEFAULT);
echo $conn."----selecting\n\n";
while (oci_fetch($stmt)) {
echo $conn . " [" . oci_result($stmt, "TEST") . "]\n\n";
}
echo $conn . "----done\n\n";
}
create_table($c1);
insert_data($c1); // Insert a row using c1
insert_data($c2); // Insert a row using c2
select_data($c1); // Results of both inserts are returned
select_data($c2);
rollback($c1); // Rollback using c1
select_data($c1); // Both inserts have been rolled back
select_data($c2);
insert_data($c2); // Insert a row using c2
commit($c2); // Commit using c2
select_data($c1); // Result of c2 insert is returned
delete_data($c1); // Delete all rows in table using c1
select_data($c1); // No rows returned
select_data($c2); // No rows returned
commit($c1); // Commit using c1
select_data($c1); // No rows returned
select_data($c2); // No rows returned
drop_table($c1);
echo "</pre>";
?>
Note
Notă: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: » http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Notă: The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that queries issued against one handle are also applied to the other handles, because they are the same handle. This behaviour is demonstrated in Example 1 below. If you require two handles to be transactionally isolated from each other, you should use oci_new_connect() instead.
Notă: In PHP versions before 5.0.0 you must use ocilogon() instead. This name still can be used, it was left as the alias of oci_connect() for downwards compatability. This, however, is deprecated and not recommended.
Vedeţi de asemenea
- oci_pconnect() - Connect to an Oracle database using a persistent connection
- oci_new_connect() - Establishes a new connection to the Oracle server
- oci_close() - Closes Oracle connection
oci_connect
03-Jul-2009 08:55
11-May-2009 06:04
ONE ALTERNATIVE OF CONNECT IN ORACLE RAC "Real Application Clusters"
<?php
$dbstr ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip1)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco1)))";
$dbstr1 ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip2)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco2)))";
if(!@($conn = oci_connect('user','password',$dbstr1)))
{ $conn = oci_connect('user','password',$dbstr) or die (ocierror()); }
?>
01-Apr-2009 08:40
The docs seem short on information if you want to connect to an Oracle database on a different host. Here's the info shamelessly copied from The Underground PHP Oracle Manual:
If you are running Oracle Database XE on a machine called mymachine, and the PHP-enabled web server is
on the same machine, you could connect to the HR schema with:
$c = oci_connect('hr', 'hrpwd', 'mymachine/XE');
In this guide, we assume the database is on the same machine as Apache and PHP so we use localhost:
$c = oci_connect('hr', 'hrpwd', 'localhost/XE');
Depending on your network configuration, you may need to use the equivalent IP address:
$c = oci_connect('hr', 'hrpwd', '127.0.0.1/XE');
The Easy Connect string is JDBC-like. The Oracle 10g syntax is:
[//]host_name[:port][/service_name]
If PHP links with Oracle 11g libraries, the enhanced 11g syntax can be used:
[//]host_name[:port][/service_name][:server_type][/instance_name]
26-Jan-2009 05:59
Regarding the character set the is to be specified, it should be noted that it has to be the character set the client wishes to recieve and not the character set of the database.
Using this parameter, Oracle will convert the character set of the internal database to the character set specified by the client in this parameter.
22-Nov-2008 05:35
Hi, I use Oracle Database 10g Express Edition Release
10.2.0.1.0 on a Linux workstation for dev purposes, along
with Apache 2 and PHP5. So far I have used it on Kubuntu 8.04.
To get things working on a recently installed notebook with openSUSE
11.0 was a bit more complicated. So I hope someone will be able to
benefit from our experiences. Here is our howto:
# Use the package manager to install the packages php5-pear and
php5-dev, if not installed yet.
# Download the instantclient_11_1, zip files basic, sdk, sqlplus from the Oracle web site
# Switch to user root here, since not all commands to some work sudo
# Unzip these files to /opt/oracle/.
# As a result you will see a dir instantclient_11_1 appearing.
ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
/opt/oracle/instantclient_11_1/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
/usr/lib/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libnnz11.so \
/usr/lib/libnnz11.so
ldconfig # to make sure the system will be able to find the libs
pecl install oci8 # interactively enter option 1,
# then instantclient,/opt/oracle/instantclient_11_1,
# then enter
# if needed, add extension=oci8.so to your php.ini
/etc/init.d/apache2 reload
# finished!
Kind regards,
Nico den Boer
21-Jul-2008 08:16
From PHP 5.3 onwards:
A new OCI_CRED_EXT flag can be passed as the "session_mode" parameter
to oci_connect(), oci_new_connect() and oci_pconnect().
$c1 = oci_connect("/", "", $db, null, OCI_CRED_EXT);
This tells Oracle to do external or OS authentication, if configured
in the database.
OCI_CRED_EXT can only be used with username of "/" and a empty
password. Oci8.privileged_connection may be On or Off.
OCI_CRED_EXT is not supported on Windows for security reasons.
The new flag may be combined with the existing OCI_SYSOPER or
OCI_SYSDBA modes (note: oci8.privileged_connection needs to be On for
OCI_SYSDBA and OCI_SYSOPER), e.g.:
$c1 = oci_connect("/", "", $db, null, OCI_CRED_EXT+OCI_SYSOPER);
30-Jun-2008 11:33
If you want to specify a connection timeout in case there is network problem, you can edit the client side (e.g. PHP side) sqlnet.ora file and set SQLNET.OUTBOUND_CONNECT_TIMEOUT. This sets the upper time limit for establishing a connection right through to the DB, including the time for attempts to connect to other services. It is available from Oracle 10.2.0.3 onwards.
In Oracle 11.1, a slightly lighter-weight solution TCP.CONNECT_TIMEOUT was introduced. It also is a sqlnet.ora parameter. It bounds just the TCP connection establishment time, which is mostly where connection problem are seen.
The client sqlnet.ora file should be put in the same directory as the tnsnames.ora file.
20-Jun-2008 10:46
If PHP is built with Oracle 9.2 or greater client libraries, the
charset parameter is used to determine the character set used by the
Oracle client libraries. When PHP is built with older Oracle client
libraries, or if the parameter is not passed, Oracle NLS environment
variables such as NLS_LANG will be used to determine the character
set.
The character set does not need to match that used by the database.
If it doesn't, Oracle will do its best to convert data to and from the
database character set. Depending on the character sets, this may not
which may always be give usable or valid results, and it can reduce
overall performance
Because passing the parameter removes the environment look up, it can
improve connection performance
13-Sep-2006 04:42
When you are using Oracle 9.2+ I would say that you MUST use the CHARSET parameter.
Of course, you will not notice it until there is accented character... so just specify it and you will avoid a big headache.
So for example here is our Oracle internal conf:
select * from nls_database_parameters;
PARAMETER VALUE
------------------------------ ----------------------------------------
…
NLS_LANGUAGE AMERICAN
NLS_TERRITORY AMERICA
NLS_ISO_CURRENCY AMERICA
NLS_CHARACTERSET WE8ISO8859P15
…
And there our oci_connect call:
$dbch=ocilogon($user,$pass,$connectString,"WE8ISO8859P15");
Without that, you will get question mark (inversed), squares… instead of most accented character.
Don’t forget to use that for writing as well as for reading.
24-Jul-2006 04:30
For use PHPv5 functions in PHPv4 i use simple script:
<?php
$funcs=array(
'oci_connect'=>'OCILogon',
'oci_parse'=>'OCIParse',
'oci_execute'=>'OCIExecute',
'oci_fetch'=>'OCIFetch',
'oci_num_fields'=>'OCINumCols',
'oci_field_name'=>'OCIColumnName',
'oci_result'=>'OCIResult',
'oci_free_statement'=>'OCIFreeStatement',
);
// yoy can add yours pairs of funcs.
foreach ($funcs as $k=>$v)
{
if (!function_exists($k))
{
$arg_string='$p0';
for ($i=1;$i<20;$i++) {
$arg_string.=',$p'.$i;
}
eval ('function '.$k.' () {
list('.$arg_string.')=func_get_args();
return '.$v.'('.$arg_string.');
}
');
}
}
?>
simple, but it work. :-)
02-Jun-2006 02:49
Here are the translate of some functions from ORA to OCI:
<?php
function Ora_Logon($usuario, $password)
{
$con = oci_connect($usuario,$password);
return $con;
}
function Ora_Open($conexion) {
$cursor[0]=$conexion;
return $cursor;
}
function Ora_Parse(&$cursor, $consulta) {
$cursor[1]=oci_parse($cursor[0],$consulta);
return $cursor;
}
function Ora_Exec(&$cursor) {
oci_execute($cursor[1]);
$cursor[2]=1;
return $cursor;
}
function Ora_Fetch(&$cursor)
{
if ($cursor[2] == 1) $cursor[2]=0;
return oci_fetch($cursor[1]);
}
function Ora_GetColumn(&$cursor, $indice)
{
if ($cursor[2] == 1) {
Ora_Fetch($cursor);
$cursor[2]=0;
}
$valor = oci_result($cursor[1],$indice+1);
return $valor;
}
function Ora_Close(&$cursor)
{
unset($cursor[1]);
}
function Ora_Logoff($conexion) {
}
?>
07-Nov-2005 01:08
lost oracle connection. need restart apache?
Temporarely you can prevent 'connection lost' by using folowing script (use it at your own risk):
<?php
$rnum=rand(0,99999999);
$dbcon = oci_new_connect('XXXXX', 'XXXXXX',
'
(DESCRIPTION =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = XXX.XXX.XXX.XXX)
(PORT = 1521)
(HASH = '.$rnum.')
)
(CONNECT_DATA =(SID = XXX))
)
');
?>
07-Nov-2005 08:44
This note is an addendum to note#58378
Seems to be a good workaround set the oracle_home and/instead of the tns_admin.
tnsnames.ora must to be located in
$ORACLE_HOME/network/admin
and in
$TNS_ADMIN/ (if you use it)
---
Best Regards,
Domenico
02-Nov-2005 10:44
Using tnsnames.ora
Apache 2
php 5.0.5
Oracle 10 IstantClient
PHP half of times return this error:
OCISessionBegin: ORA-24327: need explicit attach before authenticating a user in ...
In Oracle manual I find:
ORA-24327 need explicit attach before authenticating a user
Cause: A server context must be initialized before creating a session.
Action: Create and initialize a server handle.
I resolved using Easy Connect Naming Method.
Notice of this problem in bug#29779.
---
Best Regards,
Domenico
28-Oct-2005 12:19
Our tnsnames.ora uses the SERVICE_NAME=mydb - which for some reason wont work with PHP even though it works fine with tnsping. Using SID=mydb worked and a connection was established.
