I'm not sure from your comment whether trying to echo the contents of the server.pem
file failed or if you meant the whole script. Hopefully the code below will help identify where the issue(s) is/are!
<?php
$debug=true;
$cert='/full/path/to/server.pem';/* this should be outside the document root */
$keytype='PRIVATE KEY';/* this is here because in testing I have an `RSA PRIVATE KEY` */
if( realpath( $cert ) ){
/* The file exists at the path given: read the contents */
$priv_key = openssl_pkey_get_private( file_get_contents( realpath( $cert ) ) );
if( $priv_key ) {
$keyData = openssl_pkey_get_details( $priv_key );
$keyData['key'] = str_replace( '-----BEGIN '.$keytype.'-----', '', $keyData['key'] );
$keyData['key'] = trim( str_replace( '-----END '.$keytype.'-----','',$keyData['key'] ) );
echo $keyData['key'];
} else {
echo $debug ? 'failed to read private key' : 'error #1';
}
} else {
echo $debug ? 'unable to find ' . $cert : 'error #2';
}
?>
As a possible alternative, as you say that the .pem
file is in the same directory as the php script, perhaps try:
$data=file_get_contents(realpath(__DIR__.DIRECTORY_SEPARATOR.'server.pem'));
echo $debug ? $data : '';
$priv_key = openssl_pkey_get_private( $data );
/*
I tried using the path ( `c:/wwwroot/certificates/server.pem` ) as the parameter to the
`openssl_pkey_get_private` rather than actually reading the contents into a string
but that failed. The method above however worked for me when the cert was in the same dir.
*/