Authentication failed for root using public key when using ssh2_auth_pubkey_file()

I am trying to use ssh using the public key on PHP. I created ssh keys and assigned to droplet successfully. And I can access the root on the terminal without any issue.

As there is a permission issue, I copied the keys to /var/www/html/.

But I am getting an error “ssh2_auth_pubkey_file(): Authentication failed for root using public key:”

Here is my code:

$host = ‘’; //Droplet ip $port = 22; $user = ‘root’; $pass = ‘pass’; $pubkey = ‘./.ssh/’; $prikey = ‘./.ssh/id_rsa’;

$conn = ssh2_connect( $host, $port ); $auth = ssh2_auth_pubkey_file( $conn, $user, $pubkey, $prikey, $pass );

if ( $auth ) { echo ‘Public Key Authentication Successful.’ . PHP_EOL; } else { echo ‘Public Key Authentication Failed.’ . PHP_EOL; }

Please help.

Show comments

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

I was able to resolve this issue by not using a passphrase! I generated a new key with no passphrase. I think this is a bug with ssh2_auth_pubkey_file function.

Thank you

Hi @rahulna.

The error in this case seems to be that the keys were generated by the root user, but they need to be accessible by the web server group/owner, usually - www-data. To confirm this, you can try and use the file_get_contents method and dump the result from the command using var_dump most probably it would say it doesn’t have enough permissions.

I’ll recommend configuring the key’s ownership and permissions to be accessible from the user that’s being used by your WebService -either Apache or Nginx.

Regards, KDSys