oci_pconnect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_pconnectConnect to an Oracle database using a persistent connection

Descrição

oci_pconnect ( string $username , string $password , string $connection_string = ? , string $character_set = ? , int $session_mode = ? ) : resource

Creates a persistent connection to an Oracle server and logs on.

Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FPM process). See the OCI8 Connection Handling and Connection Pooling section for more information.

Parâmetros

username

The Oracle user name.

password

The password for username.

connection_string

Contém uma Oracle instance a conectar. Isso pode ser uma » Easy Connect string ou num Connect Name de um arquivo tnsnames.ora, ou ainda o nome de uma instância local Oracle.

Se não especificado o PHP utilizará variáveis de ambiente como TWO_TASK (no Linux) ou LOCAL (no Windows) e ORACLE_SID para determinar a Oracle instance a conectar.

Para utilizar o método via Easy Connect, o PHP precisa ter sido compilado com as bibliotecas cliente Oracle 10g ou maiores. Uma string Easy Connect para o Oracle 10g tem a forma: [//]host_name[:port][/service_name]. Do Oracle 11g a sintaxe é: [//]host_name[:port][/service_name][:server_type][/instance_name]. Nomes de serviço podem ser encontrados ao rodar o utilitário Oracle lsnrctl status na máquina servidora do banco de dados.

O arquivo tnsnames.ora pode estar em um Oracle Net search path, que inclui $ORACLE_HOME/network/admin e /etc. Alternativamente é possível configurarTNS_ADMIN de forma que $TNS_ADMIN/tnsnames.ora seja encontrado. Tenha certeza que o servidor web tem acesso de escrita nesse arquivo.

character_set

Determina o conjunto de caracteres utilizado pelas bibliotecas Oracle Client. O conjunto de caracteres não precisa bater com o utilizado pelo banco de dados. Se eles não baterem, o Oracle fará a melhor conversão possível dos dados de e para o conjunto de caracteres do banco de dados. Dependendo dos charsets isso pode ocasionar dados não utilizáveis. Conversão também aumenta o processamento.

Se não especificado, as bibliotecas Oracle Client determinam o charset da variável de ambiente NLS_LANG.

Passar esse parâmetro pode reduzir o tempo necessário a conexão.

session_mode

Este parâmetro está disponível desde o PHP 5 (PECL OCI8 1.1) e aceita os seguintes valores: OCI_DEFAULT, OCI_SYSOPER e OCI_SYSDBA. Caso esteja especificado OCI_SYSOPER ou OCI_SYSDBA, esta função tentará estabelecer uma conexão privilegiada utilizando credenciais externas. Conexões privilegiadas estão desativadas por padrão. Para ativá-las é preciso configurar oci8.privileged_connect para On.

O PHP 5.3 (PECL OCI8 1.3.4) introduziu o valor OCI_CRED_EXT. Isso informa o Oracle para utilizar autenticação External ou OS, que precisa ser configurado no banco de dados. A flag OCI_CRED_EXT somente pode ser utilizado com o usuário "/" e uma senha em branco. oci8.privileged_connect pode estar On ou Off.

OCI_CRED_EXT pode ser combinado com OCI_SYSOPER ou OCI_SYSDBA.

OCI_CRED_EXT não é suportado no Windows por razões de segurança.

Valor Retornado

Returns a connection identifier or false on error.

Exemplos

Exemplo #1 Basic oci_pconnect() Example using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn oci_pconnect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

See oci_connect() for further examples of parameter usage.

Notas

Nota: Starting with PHP 5.1.2 and PECL OCI8 1.1, the lifetime and maximum number of persistent Oracle connections per PHP process can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

Veja Também

add a note add a note

User Contributed Notes 2 notes

up
5
php at jaggard dot org dot uk
15 years ago
[Editor's note: OCI8 1.3 should not experience the problem described in this user comment. The first use of such a connection will return an Oracle error which will trigger a cleanup in PHP.  Subsequent persistent connection calls will then succeed.  For high availability you might consider doing consecutive oci_pconnect calls in your script.]

If you connect using oci_pconnect and the connection has logged you off but is still valid, there seems to be no way to re-use that connection. The next time I try oci_pconnect and then perform an oci_execute operation, I get a "ORA-01012: not logged on" warning. This problem remains, even if I close the connection using oci_close. I ended up with the following (rather annoying) code.

<?php
   
function getOracleConnection()
    {
      if (!
function_exists('oci_pconnect'))
        return
false;
     
$toReturn = oci_pconnect('user', 'pass', 'db');
      if (
$testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@
oci_execute($testRes))
          if (@
oci_fetch_array($testRes))
            return
$toReturn;
     
oci_close($toReturn);
      if (!
function_exists('oci_connect'))
        return
false;
     
$toReturn = oci_connect('user', 'pass', 'db');
      if (
$testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@
oci_execute($testRes))
          if (@
oci_fetch_array($testRes))
            return
$toReturn;
     
oci_close($toReturn);
      if (!
function_exists('oci_new_connect'))
        return
false;
     
$toReturn = oci_new_connect('user', 'pass', 'db');
      if (
$testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@
oci_execute($testRes))
          if (@
oci_fetch_array($testRes))
            return
$toReturn;
     
oci_close($toReturn);
      return
false;
    }
?>
up
1
gotankersley at NOSPAM dot com
11 years ago
Installed on CentOS 6.2, and had lots of trouble getting it to recognize tnsnames.ora.  The fix for me was:

1. Make sure apache is getting the TNS_ADMIN env variable by putting it in the /etc/init.d/httpd file:
TNS_ADMIN=/usr/lib/oracle/11.2/client64/network/admin
export PATH TNS_ADMIN

This can be debugging in PHP by <?php echo system('env'); ?> and by verifying that TNS_ADMIN is there.

2. Make sure to use the name at the beginning of the tnsnames.ora file - not the SID (although ideally they should match.  However, if the name at the beginning is XXXX.world then pconnect will expect this - not the SID)
To Top