Database Connection Settings
Craft supports several database connection settings that give you control over how Craft connects to the database.
Ultimately, database connection settings must be set from
config/db.php, but we recommend you initially set them as environment variables (such as in your
.env file), and then pull the environment variable value into
config/db.php using getenv().
For example, in a new Craft 3 project, your
.env file should define these environment variables:
ENVIRONMENT="dev" SECURITY_KEY="" DB_DSN="mysql:host=<host>;port=<port>;dbname=<dbname>" DB_USER="root" DB_PASSWORD="" DB_SCHEMA="public" DB_TABLE_PREFIX=""
The variables that start with
DB_ are database connection settings, and they get pulled into
config/db.php like this:
return [ 'dsn' => getenv('DB_DSN'), 'user' => getenv('DB_USER'), 'password' => getenv('DB_PASSWORD'), 'schema' => getenv('DB_SCHEMA'), 'tablePrefix' => getenv('DB_TABLE_PREFIX'), ];
If you installed Craft before 3.4 was released, you will have
DB_PORT environment variables (a well as corresponding values in
config/db.php) instead of
DB_DSN. Both approaches work, but setting
DB_DSN instead is recommended in Craft 3.4 and later.
We recommend this environment variable approach for two reasons:
- It keeps sensitive information out of your project’s codebase. (
.envfiles should never be shared or committed to Git.)
- It makes collaborating with other developers easier, as each developer can define their own settings without overwriting someone else’s settings.
Here’s the full list of database connection settings that Craft supports:
An array of key => value pairs of PDO attributes to pass into the PDO constructor.
For example, when using the MySQL PDO driver (http://php.net/manual/en/ref.pdo-mysql.php),
if you wanted to enable a SSL database connection (assuming SSL is enabled in MySQL
can connect via SSL, you'd set these:
[ PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem', PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem', PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem', ],
The charset to use when creating tables.
The Data Source Name (“DSN”) that tells Craft how to connect to the database.
DSNs should begin with a driver prefix (
pgsql:), followed by driver-specific parameters.
- MySQL parameters: http://php.net/manual/en/ref.pdo-mysql.connection.php
- PostgreSQL parameters: http://php.net/manual/en/ref.pdo-pgsql.connection.php
The database password to connect with.
The schema that Postgres is configured to use by default (PostgreSQL only).
If you're sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), then you can set a table prefix here to avoid table naming conflicts per install. This can be no more than 5 characters, and must be all lowercase.
The database username to connect with.