Yii2 MySQL remote SSL connection

'db' => [
	'class' => 'yii\db\Connection',
	'dsn' => 'mysql:host=REMOTE.HOST.MYSQL;dbname=remote_db_name',
	'username' => 'remote_db_user',
	'password' => 'remote_db_password',
	'charset' => 'utf8',
	'attributes' => [
		PDO::MYSQL_ATTR_SSL_KEY => dirname(dirname(__DIR__)) . '/common/config/ssl/client-key.pem',
		PDO::MYSQL_ATTR_SSL_CERT => dirname(dirname(__DIR__)) . '/common/config/ssl/client-cert.pem',                
		PDO::MYSQL_ATTR_SSL_CA => dirname(dirname(__DIR__)) . '/common/config/ssl/server-ca.pem',                
		],
],

This is assuming that the certs are within the common folder of an Yii2 advanced template project.

It’s probably also a good idea to chmod the pem files to 600 and the ssl directory to 700 so that only the user

Where are the pem files?

/var/lib/mysql/*.pem

2 thoughts on “Yii2 MySQL remote SSL connection”

  1. I m trying to connect Google Cloud SQL database using “db” configuration in Yii2 with SSL certificates, unfortunately, not able to connect when I try, it gives me a timed-out issue.
    Below find DB configuration:
    ==============================================
    ‘db’ => [
    ‘class’ => ‘yii\db\Connection’,
    ‘dsn’ => ‘mysql:host=host IP addess;port=3306;dbname=db_name’,
    ‘username’ => ‘username’,
    ‘password’ => ‘password’,
    ‘charset’ => ‘utf8’,
    ‘attributes’ => [
    \PDO::MYSQL_ATTR_SSL_KEY => dirname(dirname(__DIR__)) . ‘/folder/client-key.pem’,
    \PDO::MYSQL_ATTR_SSL_CERT => dirname(dirname(__DIR__)) . ‘/folder/client-cert.pem’,
    \PDO::MYSQL_ATTR_SSL_CA => dirname(dirname(__DIR__)) . ‘/folder/server-ca.pem’,
    ], ],
    ============================================
    Error:
    Database Exception – yii\db\Exception
    SQLSTATE[HY000] [2002] Connection timed out
    Error Info: Array
    (
    [0] => HY000
    [1] => 2002
    [2] => Connection timed out
    )

    Caused by: PDOException
    SQLSTATE[HY000] [2002] Connection timed out
    =============================================
    However, if I try to connect the Cloud SQL database using MY SQL workbench using the same SSL certificate from local machine, it is working fine.

    please help how to connect cloud SQL – MySQL database to yii2 application

    1. Having never used Google’s Cloud SQL before, this is just a random guess, but do you need to whitelist the IP that you’re connecting from (aka the IP the Host of the PHP app)?

Leave a Reply

Your email address will not be published. Required fields are marked *