DB2 Version 9.7 for Linux, UNIX, and Windows

Trusted contexts in PHP applications (ibm_db2)

Starting in Version 9.5 Fix Pack 3 (or later), the ibm_db2 extension supports trusted contexts by using connection string keywords.

Trusted contexts provide a way of building much faster and more secure three-tier applications. The user's identity is always preserved for auditing and security purposes. When you need secure connections, trusted contexts improve performance because you do not have to get new connections.

Example

Enable trusted contexts, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
	echo "Explicit Trusted Connection succeeded.\n";

	if(db2_get_option($tc_conn, "trustedcontext")) {
		$userBefore = db2_get_option($tc_conn, "trusted_user");

		//Do some work as user 1.

		//Switching to trusted user.
		$parameters = array("trusted_user" => $tc_user, "trusted_password" => $tcuser_pass);
		$res = db2_set_option ($tc_conn, $parameters, 1);

		$userAfter = db2_get_option($tc_conn, "trusted_user");
		//Do more work as trusted user.

		if($userBefore != $userAfter) {
			echo "User has been switched." . "\n";
		}
	}

	db2_close($tc_conn);
}
else {
	echo "Explicit Trusted Connection failed.\n";
}

?>