I also spent hours when trying to find the reason of error:
"error getting private key".
Sometimes this error appeared, sometimes not.
My solution is using the realpath() for every parameter of openssl_pkcs7_sign. In my case the code looks like:
<?php
$Certif_path = 'certificate/mycertificate.pem';
$clearfile = "certificate/random_name";
$encfile = $clearfile . ".enc";
$clearfile = $clearfile . ".txt";
openssl_pkcs7_sign(realpath($clearfile),
realpath('.').'/'.$encfile, 'file://'.realpath($Certif_path),
array('file://'.realpath($Certif_path), PUBLIC_KEY),
array("To" => TO_EMAIL,
"From" => FROM_EMAIL,
"Subject" => ""),
PKCS7_DETACHED));
?>