title: PHP ssh2_connect to remote passwordless server
body: <p>I have setup SSH passwordless login between local client and remote server.</p>
  
  <p>Local client has private key, remote server added with local client's public key.</p>
  
  <p>local client is able to SSH/SFTP to remote server without password -> sftp remoteusr@server</p>
  
  <pre><code>---on local client machine---
  private key location -&gt; /home/localusr/.ssh/id_rsa (owner:group = localusr:localusr)
  public key path -&gt; /home/localusr/.ssh/id_rsa.pub (owner:group = localusr:localusr)
  
  ---on remote server---
  added client public key to /home/remoteusr/.ssh/authorized_keys
  </code></pre>
  
  <p>I was not able to establish SFTP connection using PHP from local client</p>
  
  <pre><code>$conn = ssh2_connect($server, $port, array('hostkey'=&gt;'ssh-rsa'));
  
  if (ssh2_auth_pubkey_file($conn, 'remoteusr', '/home/localusr/.ssh/id_rsa.pub', '/home/localusr/.ssh/id_rsa')) {
      echo "Public Key Authentication Successful";
  } else {
      die('Public Key Authentication Failed');
  }
  </code></pre>
  
  <p>I encountered this error</p>
  
  <pre><code>PHP Warning:  ssh2_auth_pubkey_file(): Authentication failed for 
  remoteusr using public key: Unable to open public key file in 
  xxx.php on line 29
  </code></pre>
  
  <p><strong>SOLUTION</strong>:</p>
  
  <p>This is due to permission issue, i think somehow apache server does not have permission to read the keys. Able to make it work by copying private and public key from</p>
  
  <pre><code>/home/localusr/.ssh/id_rsa
  /home/localusr/.ssh/id_rsa.pub
  </code></pre>
  
  <p>To</p>
  
  <pre><code>/var/www/project/id_rsa
  /var/www/project/id_rsa.pub
  and chmod 700
  </code></pre>