1

I have created an tunnel(SSH) in order to access URL's that are blocked from my local PC. This works really well, I can for example access from the browser this url http://localhost:8888 and I will get the intended content. This URL also works with the REST Client that I'm using for testing. However, if I call it from PHP:

file_get_contents('http://localhost:8888') 

I get this error each time: failed to open stream: Connection refused

So my guess is that file_get_contents doesn't work well with SSH tunnels. Is there maybe an alternative function that I could use for this purpose ?

Zed
  • 5,683
  • 11
  • 49
  • 81
  • There is no reason why that function should _not_ work via an ssh tunnel. There has to be some other difference in your setup. – arkascha Jul 13 '17 at 15:09
  • I don't know, maybe some php.ini tweak ? It doesn't make sense. – Zed Jul 13 '17 at 15:11
  • `allow_url_fopen` setting in your php.ini maybe? – Alex Howansky Jul 13 '17 at 15:16
  • well I can open pretty much everything with file_get_contents, I have a problem only with this URL from description. And yeah, allow_url_fopen is On. – Zed Jul 13 '17 at 15:24
  • Try with `curl`? – Alex Howansky Jul 13 '17 at 15:25
  • Just tried with curl from the command line, it works fine. However I can't really change the code, so I'm stick with file_get_contents. – Zed Jul 13 '17 at 15:27
  • It's the same thing with fopen() – Zed Jul 13 '17 at 16:47
  • OK guys, I have just tried with using curl extension inside the PHP and I'm getting back the same error, which is strange because curl from the command lines can connect to the URL without any problems. Is there something else I can try ? – Zed Jul 13 '17 at 16:56

1 Answers1

1

I solved this problem using php-ssh2 package.

Instalation on Ubuntu 16

sudo apt-get install php-ssh2

Usage with user name and password:

$conn = ssh2_connect($ip, 22);
ssh2_auth_password($conn, $user,$pass);
ssh2_scp_recv($conn, '/remote_path', '/local_path');

Usage with id_rsa (after ssh-copy-id)

I recommend use this method because of we probably do not want paste plain password in source code.

$conn = ssh2_connect($ip, 22);
ssh2_auth_pubkey_file($conn, $user,
    "/home/{$user}/.ssh/id_rsa.pub",
    "/home/{$user}/.ssh/id_rsa", 'secret')
ssh2_scp_recv($conn, '/remote_file', '/local_file');

Additional info

Old name of this package: libssh2-php

Docs:

http://php.net/manual/en/function.ssh2-scp-recv.php

Connected question:

How to SFTP with PHP?

Is there also possibility of use:

file_get_contents("ssh2.sftp://{$user}:{$pass}@{$ip}:22{$remote_path}"))

but I do not know how to use it with id_rsa.pub.

Daniel
  • 7,684
  • 7
  • 52
  • 76