Tuesday, May 22, 2012

Connecting to a Remote Oracle Database with PHP


1, Download Oracle Instant Client package that match with Oracle Database version
    Example: http://www.oracle.com/technetwork/topics/winsoft-085727.html
2, Unzip file to directory C:\Program Files\Oracle Instant
3, Create a new file in that same directory named tnsnames.ora
     This is an important configuration file that allows you to create kind of a local reference to a remote Oracle database server. Paste the following into that new file:
YourServiceName =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = YourHost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = YourServiceName)
    )
  )
4, Add Environment Variable to your system
-          User variable: variable name: Path , variable value:  C:\Program Files\Oracle Instant
-          System variable: add new variable name: TNS_ADMIN , variable value C:\Program Files\Oracle Instant
This environment variable ensures that PHP will be able to find your tnsnames.ora file when it tries to connect via oci_connect(), so it's important.
5, To get your PHP scripts talking to the remote Oracle server, you'll use the oci_connect() function. you'll need to enable support for the oci8 module. To do this, open up your php.ini file and uncomment (remove the leading semicolon from) the line that reads:
;extension=php_oci8.dll 
it might be possible to only restart Apache (or whatever web server you're running), so you might give that a shot first just to see if you're lucky.


Then try code connect
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = YourHost)(PORT = 1521)))(CONNECT_DATA=(SID=ServiceName)))";$conn = oci_connect("UserName","Password",$db);

if ($conn) {
            echo "Connected<br>\n";
} else {
            echo "Connected fail<br>\n";
}

Note: if you still see the message Fatal error: Call to undefined function oci_connect()
Copy all files from directory Oracle Instant to directory apache/bin

Reference:
http://www.bernzilla.com/item.php?id=784