Connecting PHP to An Oracle Instance on RedHat or CentOS 5

Here lately it seems that everyone wants to connect to Oracle, but I have to admit this was the first time someone asked me to get PHP to talk to Oracle. It was a lot less painful then I thought it would be, so here is what I did.

A long with the standard PHP RPMs you need to install a couple of additional RPMs from Oracle. These are oracle-instantclient-basic and oracle-instantclient-devel which can be downloaded from http://www.oracle.com/technetwork/database/features/instant-client/index-100365.html. You will also need php-oci8 RPM which can be download fromhttp://oss.oracle.com/projects/php/files/EL5/.

So after you have downloaded the RPMs go a head and install the packages and create the symlink for libcIntsh.so.

$ rpm -Uvh oracle-instantclient-basic-##.#.#.rpm
$ rpm -Uvh oracle-instantclient-devel-##.#.#.rpm
$ cd /usr/include/oracle/##.#/[client|client64]
$ ln –s libclntsh.so.##.# libclntsh.so

Now you are going to want to setup you environment settings, It is important to set all Oracle environment variables before starting Apache or running a PHP script,  so that the OCI8 process environment is correctly initialized. Setting environment variables in PHP scripts can lead to obvious or non-obvious problems. You can also add Instant Client library path to /etc/ld.so.conf.

$ LD_LIBRARY_PATH=/usr/lib/oracle/##.#/[client|client64]/lib:${LD_LIBRARY_PATH}
$ export LD_LIBRARY_PATH

And now for the big finish. Here is a simple connection script to test it all out.

<?php
$c = oci_connect( ‘USERNAME’,
‘PASSWORD’,
‘SERVERNAME:PORT/SERVICE_NAME’, INSTANCE_NAME’ );

if( $c ) {

$s = oci_parse( $c, ‘SELECT TABLE_NAME FROM all_tables’ );

oci_execute($s) ;

while($res = oci_fetch_array( $s, OCI_ASSOC) ) {

echo $res[‘TABLE_NAME’] . “\n”;
}

}
?>

For a complete list of function and additional install resources check out the following sites:

http://php.net/manual/en/book.oci8.php
http://wiki.oracle.com/page/PHP
http://www.oracle.com/technetwork/articles/technote-php-instant-084410.html

Leave a Reply