redreinard
redreinard

Reputation: 2044

How to setup an SSL encrypted MySQL connection with Doctrine2 in PHP (not Symfony, not Doctrine1)

I am having a hard time finding documentation / examples of how to setup an SSL encrypted connection with Doctrine2 to MySQL. I'm not using Symfony, so looking for the pure PHP path.

What I'm stuck on is basically how to convey the MYSQL_CLIENT_SSL (or MYSQLI_CLIENT_SSL) flag, and the path to the ca certificate. I can live with not verifying the certificate, but I can't live with not encrypting the connection for this task.

On the command line this would be done similar to this:

mysql --ssl-verify-server-cert --ssl-ca=/mysql-ssl-certs/ca-cert.pem --ssl -h host [etc]

In pure php using the mysql extension I think it would look something like:

$conn = mysql_connect($host, $user, $pass, false, MYSQL_CLIENT_SSL);

With mysqli (i think) it would be something like this:

$db = mysqli_init(); 
$db->ssl_set(null, null, $cert, null, null); 
$db->real_connect($host, $user, $pass, $dbname);

The question is, how do I do this with Doctrine2? Is it even possible? How do I modify the initialization for Doctrine2 to do this?

$DOCTRINE2_DB = array(
  'driver'      => 'pdo_mysql',
  'host'        => $host,
  'user'        => $user,
  'password'    => $pass,
  'dbname'      => $dbname,
  'unix_socket' => $sockpath,
);
$DOCTRINE2_EM = \Doctrine\ORM\EntityManager::create($DOCTRINE2_DB, $DOCTRINE2_CONFIG);
$EM =& $DOCTRINE2_EM; // for brevity & sanity

Upvotes: 0

Views: 3459

Answers (1)

Alex Barroso
Alex Barroso

Reputation: 859

You should be able to add an additional parameter driverOptions and set the appropiate SSL configuration for PDO

https://www.php.net/manual/es/ref.pdo-mysql.php#pdo-mysql.constants

$DOCTRINE2_DB = array(
    'driver'      => 'pdo_mysql',
    'host'        => $host,
    'user'        => $user,
    'password'    => $pass,
    'dbname'      => $dbname,
    'unix_socket' => $sockpath,
    'driverOptions' => array(
        PDO::MYSQL_ATTR_SSL_CA => '...',
        PDO::MYSQL_ATTR_SSL_CERT => '...',
        PDO::MYSQL_ATTR_SSL_KEY => '...'
    )
);

I can't test it but looking at the code here I think it should work

[EDIT BY ASKER:] Here is how it worked for me:

$DOCTRINE2_DB = array(
    'driver'      => 'pdo_mysql',
    'host'        => $host,
    'user'        => $user,
    'password'    => $pass,
    'dbname'      => $dbname,
    'unix_socket' => $sockpath,
    'driverOptions' => array(
        PDO::MYSQL_ATTR_SSL_CA => '/file/path/to/ca_cert.pem',
    )
);

Upvotes: 3

Related Questions