PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<ocilogoffocinewcollection>
view the version of this page
Last updated: Thu, 21 Aug 2003

ocilogon

(PHP 3>= 3.0.4, PHP 4 )

ocilogon -- Establishes a connection to Oracle

Description

resource ocilogon ( string username, string password [, string db])

ocilogon() returns an connection identifier needed for most other OCI calls. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

Connections are shared at the page level when using ocilogon(). This means that commits and rollbacks apply to all open transactions in the page, even if you have created multiple connections.

This example demonstrates how the connections are shared.

Example 1. ocilogon() example

<?php
print "<PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocilogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." [".ociresult($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);
print "</PRE>";
?>

See also ociplogon() and ocinlogon().



add a note add a note User Contributed Notes
ocilogon
aliquis at die dot spammers dot die dot link-net dot org
23-Oct-2003 08:39
I've had all kinds of errors with RedHat9(yuck), PHP 4.3.4RC1 and Oracle enterprice server 9.2. For some time I thought that --with-oci8 wouldn't work with Oracle9 but that wasn't the case, the solution was many steps.

1) install oracle, might require some tricks, on RedHat9 I had to put this in my .bashrc:
export ORACLE_BASE=/opt/ora9
export ORACLE_HOME=$ORACLE_BASE/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_OWNER=oracle
export ORACLE_SID=netadmdb
export ORACLE_TERM=vt100
export LD_ASSUME_KERNEL=2.4.1
export THREADS_FLAG=native
export LD_LIBRARY_PATH=$ORACLE_BASE/product/9.2/lib:$LD_LIBRARY_PATH

2) compile php, use --with-oci8

3) Make an init-script for the oracle9 database server, as default the TNS listener doesn't run so add that on aswell, example:
#!/bin/bash
export ORACLE_HOME=/opt/ora9/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_SID=netadmdb
export DISPLAY=:0
oracle_user=oracle
export oracle_user
case $1 in
start)
su - "$oracle_user"<<EOO
sqlplus /nolog<<EOS
connect / as sysdba
startup
EOS
/opt/ora9/product/9.2/bin/lsnrctl start
EOO
;;
stop)
su - "$oracle_user"<<EOO
/opt/ora9/product/9.2/bin/lsnrctl stop
sqlplus /nolog<<EOS
connect / as sysdba
shutdown immediate
EOS
EOO
;;
*)
echo "Usage: ora9 [start|stop]"
;;
esac

4) Configure Apache. For some reason it requires some tweaking with environment variables, in the begining I put those in the PHP-script with putenv, later in the httpd.conf with SetEnv and the mod_env module. But I was told to not do that and instead set them in the init script for Apache. So I copied apachectl to /etc/init.d and edited envvars in $APACHE_PATH/bin. First I added all kinds of env variables until I got it to work, and then I removed them one at a time and came to the following minimal configuration:
LD_LIBRARY_PATH="/usr/local/apache2/lib:$LD_LIBRARY_PATH"
ORACLE_HOME=/opt/ora9/product/9.2
LANG=sv_SE
export LD_LIBRARY_PATH ORACLE_HOME LANG

Earlier I had added NLS_LANG and TNS_ADMIN above those mentioned above (point 1), but it seems those aren't needed really. So no need for TWO_TASK or ORACLE_SID, only needed one is ORACLE_HOME and if you get missing/invalid option for your OCILogon set LANG to something else like I did. Someone earlier said it might have to do with UTF8.

So if you are sure lsncrtl are started and that you have the correct env-variables set in your $APACHE_PATH/bin/envvars you can just use something like:

$iDBConn=OCILogon("user","pass","netadmdb");

in your PHP-script and it should work.
Hope this helps someone.
matt at ZZZbadgernet dot freeserveZZZ dot co dot uk
07-Oct-2003 09:10
I've had some trouble with this for a while.  I've finally sussed it.

Note that the remote connection only started working for me when I specified the complete "GLOBAL_DBNAME" available from the listener.ora file as the SERVICE_NAME.

For a local database:
--------------------------------------------------------
putenv("ORACLE_SID=DBSID");
putenv("ORACLE_HOME=/usr/local/oracle/product/8.1.7_64");

$username = "username";
$passwd = "password";
$db="";

echo "Attemping database connection...";
$conn = @OCILogon($username,$username,$db);
if (!$conn)
{
        echo "...FAILED\n";
        if (OCIError($conn))
        {
                $erra=OCIError($conn);
                dodberror("SQL Error: $erra[code] $erra[message]");
        }
        exit;
}
else
{
        echo "...connected\n<BR>";

--------------------------------------------------------

For a remote (or local) database:

--------------------------------------------------------
putenv("ORACLE_HOME=/usr/local/oracle/product/8.1.7_64");

$username = "username";
$passwd = "password";
$db="(DESCRIPTION=
          (ADDRESS_LIST=
            (ADDRESS=(PROTOCOL=TCP)
              (HOST=remotenode)(PORT=remoteport)
            )
          )
           (CONNECT_DATA=(SERVICE_NAME=DBSID.domain))
     )";

echo "Attemping database connection...";
$conn = @OCILogon($username,$username,$db);

if (!$conn)
{
        echo "...FAILED\n";
        if (OCIError($conn))
        {
                $erra=OCIError($conn);
                dodberror("SQL Error: $erra[code] $erra[message]");
        }
        exit;
}
else
{
        echo "...connected\n<BR>";
}
--------------------------------------------------------
Tomasz dot Kokowski at put dot poznan dot pl
03-Oct-2003 01:45
Getting PHP 4.3.3 (and lower versions) to work
with Apache v2.xxx and Oracle 8i was easy.

But just after Oracle upgrade to 9i ugly message
appeared when ocologon () was called :

Warning: ocilogon(): _oci_open_session: OCIHandleAlloc OCI_HTYPE_SVCCTX: OCI_INVALID_HANDLE

What we should do? All environment variables
has been set correctly, tnsnames too (it worked
under oracle 8i).

The solution was posted 2003-09-17 22:24 by
Andy Hassall (andy@andyh.co.uk) responding in
news:comp.lang.php threat "PHP & OCI9. No such..."

"Also check file permissions on the Oracle home; by default, Oracle 9i installs the Oracle home with restricted permissions (this differs from 8i). You may need to grant at least Read and Execute permissions to the web server's user."

That's correct. I've added r-x permissions for others
for oracle user $HOME and got nice message - logged
with success!

Tomasz Kokowski
Franks
20-Aug-2003 09:52
For those having Oracle errors, I find out that little something, while using Apache2. I don't know if this applies also to Apache 1.x, but for Apache2, this is the ultimate solution!

Especially with ORA-12154 and ORA-12505, some said to write the following code in your php script, but if you have access to the configuration or your web server, DON'T!

<?php
putenv
("ORACLE_SID=TESTDB");
//putenv("ORACLE_HOME=/oracle/ora90");
//putenv("TNS_ADMIN=/oracle/ora90/network/admin");
$username "scott";
$passwd "tiger";
$db="(DESCRIPTION=
          (ADDRESS_LIST=
            (ADDRESS=(PROTOCOL=TCP)
              (HOST=yourTargetMachine)(PORT=1521)
            )
          )
           (CONNECT_DATA=(SERVICE_NAME=TESTDB))
     )"
;
$conn OCILogon($username,$passwd,$db);
...
?>

All right, like I said, if you have access to the configuration of apache, there is a file in $APACHE2/bin called envvars. Simply put the necessary environment variables needed by Oracle in this file: ORACLE_SID, ORACLE_BASE, ORACLE_HOME and myself I also added LD_LIBRARY_PATH with oracle directories.

At first, my problem was that I didn't had all the environment sets when rebooting the server, but if I'd stop apache, then restart it, while beeing root, all the environment was there. Setting the envvars file correctly solved the reboot problem.

Hope this will help!
Franks
oddbec-removethis at online dot no
09-Jul-2003 08:35
I Had trouble with OCILOGON not wanting to login/connect properly.

Errormessage: Error while trying to retrieve text for error ORA-12514.

This error suddenly occured after I rebooted the webserver (Which had been running for a couple of months by then).

How was I supposed to know what last changes had been done the last months?

The solution to my troubles was putenv :-)

In the beginning of the php-script I just added:
putenv("ORACLE_SID=MyDB");

That was it! =)

-Odd Arne Beck-
NOSPAMPLZ!esartoni at omniaglobal dot net
27-May-2003 05:12
I had a little problem with ocilogon but only with RedHat 8.0. It always returned some kind of error during connection like 'OCISessionBegin - ... invalid character', or 'OCISessionBegin - ... missing or invalid option in ...'

I have finally found what is this problem! You have to change your LANG enviroment variable disabling UTF-8. Example: LANG=en_US.UTF-8 should become LANG=en_US.
nino at lkp dot ifsab dot se
21-May-2003 07:17
After a long time trying to get a select to work I found something that is not in the comments. TWO_TASK environment variable must be set to the database alias in tnsnames.ora for it to work with my setup.
RH 9.0 (Apache 2.0)
PHP 4.2.2 with SRPM recompiled with oci8 support
Oracle 8.1.7.0.0 client installed

Hope it helps some poor soul.
/Nicke
john at john-warner dot com
21-Nov-2002 08:13
In addition to the earlier posts here is a further explaination;

Problem: Regular and Remote authentication does not work using Windows 2000 + PHP and Oracle 8i, 9i.

Secondary Issue if using Oracle 9.2.0.1
    When using Oracle 9.2.0.1 the Error structure returned by Oracle is different than expected by PHP. As a result there will be no legible error message other than the following;
    Warning: _oci_open_server: in ...

Using Oracle 9.0.1.1 the error message returned is any of the following depending on your situation;
   
Warning: _oci_open_server: ORA-12638: Credential retrieval failed in ...
Warning: _oci_open_server: ORA-12154: TNS:could not resolve service name in ...
Warning: _oci_open_server: ORA-12505: TNS:listener could not resolve SID given in connect descriptor in ...
   
Resolution:
In order to get this to work properly you need to do the following;
In reference to ORA-12638: Credential retrieval failed in ...
you need to edit your sqlnet.ora file and change the
SQLNET.AUTHENTICATION_SERVICES = (NTS) to
SQLNET.AUTHENTICATION_SERVICES = (NONE)
The reason is that using NTS validation on a Windows 2000 machine essentially means Kerberos.
Using (NONE) will tell oracle not to expect kerberos "Credentials" as a means of validation. In turn it will use the oracle authentication for a database user.

In reference to ORA-12154 and ORA-12505 you need to do the following;
In your php code you are using to connect you need to copy the section in tnsnames.ora
into a variable.
For example;
<?php
putenv
("ORACLE_SID=TESTDB");
//putenv("ORACLE_HOME=/oracle/ora90");
//putenv("TNS_ADMIN=/oracle/ora90/network/admin");
$username "scott";
$passwd "tiger";
$db="(DESCRIPTION=
           (ADDRESS_LIST=
             (ADDRESS=(PROTOCOL=TCP)
               (HOST=yourTargetMachine)(PORT=1521)
             )
           )
             (CONNECT_DATA=(SERVICE_NAME=TESTDB))
      )"
;
$conn OCILogon($username,$passwd,$db);
if (!
$conn)
{
    echo 
"Connection failed";
    echo 
"Error Message: [" OCIError($conn) . "]";
    exit;
}
else
{
    echo 
"Connected!";
}
...
?>
I left the ORACLE_HOME and TNS_ADMIN putenv lines commented out and your need for them depends on which web server you are using. If you are using Apache, you may need both.
If you are using Microsoft IIS you may need ORACLE_HOME. Putting it in can't hurt and it appears PHP may read them if they are there but either way you should be working at this
point.

Live long and prosper.
DBrown3205 at aol dot com
09-Apr-2002 09:49
If you're running an apache server, make sure you have php setup as a module. Then just include the environment variables in the apache config, and use all 3 parts of the ocilogon. You don't even have to copy the tsnnames.ora definition, just use the standard sid
gaoweibin at 263 dot net
29-Jan-2002 12:21
In Oracle 9i, "sys" user logon must "as sysdba" or "as sysoper".

I use this function cannot logon to Oracle 9i as "sys" successful.
i990712 at dei dot isep dot ipp dot pt
03-Oct-2001 07:53
For those of you who are having Oracle errors: ORA-12154 or ORA-12505 or ORA-01005 do the folowing:

The folowing precedures have been tested when connecting to a HP UX with Oracle 7.x using of couse the OCI8 as the client interface.

Add those lines to the web server config files or set and export those ones before the web server starts.

On Apache add these lines to httpd.conf:

SetEnv ORACLE_HOME /usr/local/oracle
SetEnv ORACLE_SID <sid>
SetEnv LD_LIBRARY_PATH /usr/local/oracle/lib
SetEnv TNS_ADMIN /usr/local/oracle/tnsnames.ora
SetEnv TWO_TASK /usr/local/oracle/tnsnames.ora
SetEnv NLS_LANG  English_America.WE8ISO8859P1
SetEnv ORACLE_BASE /usr/local

When calling the OCILogon do this:

$db = "  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP) (HOST =server_ip_or_dns_name)(PORT = 1521))
    (CONNECT_DATA= (SID = _sid_))
    )";

The previous definition is a copy of the service definition that is stored in the tnsnames.ora file.

Next, call the OCILogon function using the folowing format:

OCILogon("user/password","password", $db);

To avoid ORA-01005 error, set the NLS_LANG environment variable to English_America.WE8ISO8859P1 ( some other values may work...but we have found that this one works for us )

To avoid ORA-12154 and ORA-12505, use the service definition as the OCILogon third parameter.

I'd like to thanks to a friend of mine a.k.a Rosa for the user/password tip.

Regards
Miguel Carvalho
me at dglewis dot com
09-Aug-2001 08:14
Some trouble-shooting notes:<br>
When using Apache with dso support and php as a loadable module, be sure to stop/start your web server between tnsnames.ora changes (sending HUP to apache "apachectl restart" doesn't appear to flush cached connect string).<br>
You'll see your changed connect strings in the listener log file.<p>
TNSNAMES.ORA:<br>
This is a very simple file to manage, yet can be very picky about your syntax.  Simply ensure that you follow one of these two examples:<br>
Legacy SID:<br>
alias-or-sidname =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(Host = hostname-or-ipaddress)(Port = 1521))
    (CONNECT_DATA =
      (SID = sidname)
    )
  )<br>
8i SERVICE NAME:<br>
hostname.domainname.com =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = hostname-or-ipaddress)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = servicename)
    )
  )</p>
Additional notes:<br>
- ORA/TNS-12514 error can also be caused by listener not being started.
- Ensure that httpd user (i.e. nobody) has the following in its environment (putenv is unnecessary if env is set by os via /etc/profile):
$ORACLE_SID
$ORACLE_HOME<br>
Also, some helpful resources:
- TNS Error Messages:
http://www.oradoc.com/ora817/server.817/a76999/tnsus.htm#1000527
- TNS Listener logs:
$ORACLE_HOME/network/log/...
Marinne at ilovechocolate dot com
17-May-2001 07:25
One simple but useful note:check whether your TNS Listener is running! By default, it's not started automatically when an Oracle instance is started. Login as oracle then type :

lsnrctl START

After it's started, I can sucessfully run the sample code on this page! I used to got ora-12514 error before doing this.
bluei at phpworld dot org
06-Mar-2001 06:57
check your tnsnames.ora permission.

ex)
ORACLE_HOME = /home/oracle/oracle

chmod 755 /home/oracle/oracle/network/admin -R

Yahoo!!!!!! I solved it!!!
tabish_mohd at yahoo dot com,sdodhiya at yahoo dot com
24-Feb-2001 12:45
After long research we done it:
the error is:

Warning:  _oci_open_server: ORA-12154: TNS:could not resolve service name.
OR
Warning:  _oci_open_server: ORA-12154: TNS:could not resolve service name

By setting the envornment variable doesn't work.(putenv(ORACLE_SID=TNSNAME");

now the solution is:
put the tnsname.ora contents into the variable as,

$db="(DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = RemoteServerIP)(PORT = 1521))
    (CONNECT_DATA = (SID = ORCL))
  )";

OCILogon("scott","tiger",$db);

now it will work.
c_caughlan at hotmail dot com
20-Jan-2001 12:05
If you are experiencing problems logging onto your Oracle DB, maybe a ORA-12154 error or something like that, try setting the ORACLE_HOME, ORACLE_SID, TNS_ADMIN vars in your Apache config, rather than using PutEnv() inside PHP. Its because PHP/Apache needs to know these variables upon server startup, not when it serves the PHP page. Of course, this assumes you have OCI installed locally on the webserver, if you dont, no matter what variables you set and where, it just wont work.
adrian dot zimermann at ospm dot ch
14-Dec-2000 06:28
Giving the nobody account dba-privileges allows the user nobody to login as Administrator. I don't see any reason to use this privilege (and basically I don't use it on my intranet sites). PHP is able to login without this dangerous priv.
obatopaye at yahoo dot com
19-Oct-2000 02:45
To avoid the ORACLE_SID problem/not being able to connect to database:
 
Apache parent thread runs as 'root' - setup root's profile to have ORACLE variables - then when script starts Apache - also initialize profile to current shell.

user 'nobody' inherits all root's profile.
david at ethell dot com
15-Sep-2000 01:12
This last note put me in the right direction. I su'd as nobody and found my problem was the permissions on the /home/oracle directory. I needed to add nobody to my dba group and then give /home/oracle group read and group execute permissions and everything started working.
lhf at mail dot 2932 dot com dot cn
14-Jul-2000 10:39
While login to remote oracle server,you should setup oracle client first.If failed with error ora-12154,Please if you web server account can acess the tnsnames.ora file or not.One way is login as root then 'su nobody' and set the correct envrionment,run sqlplus to test if it works fine.
vasquez at sp-am dot dot eu
13-May-2000 05:54
If you try to connect to an Oracle7 database,
and you get the "ora-01005, null password given errror", make sure to do the following:<br>
-install net8 (ok, you already did)<br>
- use net8 as ORACLE_HOME *for the webserver*!<br>
- add the user of the httpd process  (nobody or www or whatever) to the group oracle<br>
- use the TWO_TASK env for connecting
rkohli at xperts dot com
01-Apr-2000 02:32
Regarding connecting to an Oracle Db on NT from Linux, here is what you need to do. Little Oracle knowledge is a prerequisite.

1. Install Oracle database client onto Linux.
2. Once installed on Linux, modify the tnsanmes.ora file to create an alias to the database running on the NT box. Follow the syntax already in the tnsnames.ora file
3. Depending on the version of Oracle you have and the Oracle Database has the listener running there is a utility called tnsping(xx) that you can use to verify that you can hit a remote 0racle database syntax is tnsping <alias in tnsnames.ora>
4. You could use sqlplus to conenct to the remote database to verify the login process works. Remember to use login_id@tnsnames_alias/password
5. Once you have gotten this far PHP should be able to hit the database. Give it a shot. You might need to tool around the PHP config to get things to work. use the phpinfo function to debug, its rather useful.
akolk at gelrevision dot nl
05-Aug-1999 12:04
If you have Oracle8i installed, link against those directories. That will give you a number of usefull performance boosts while fetching data from the database. These optimizations will only work if your client libraries and server libraries are Oracle8i
Jeremy dot Bouse at UnderGrid dot net
20-Jul-1999 11:08
The ORACLE_SID should be known as it is the ID that designates the database you are wishing to connect to... Your oracle DBA account should have this set and running oraenv should recommend the correct SID if properly setup.

<ocilogoffocinewcollection>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST