Create a socket connection using PHP

Open a Unix socket connection to Cloud SQL for PostgreSQL by using the PHP Data Objects (PDO) extension.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

PHP

// $username = 'your_db_user';
// $password = 'yoursupersecretpassword';
// $dbName = 'your_db_name';
// $connectionName = getenv("CLOUD_SQL_CONNECTION_NAME");
// $socketDir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';

// Connect using UNIX sockets
$dsn = sprintf(
    'pgsql:dbname=%s;host=%s/%s',
    $dbName,
    $socketDir,
    $connectionName
);

// Connect to the database.
$conn = new PDO($dsn, $username, $password, $connConfig);

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.