0

I been trying for hours to get the name of the public folder on a remote server using an ssh2 connection.

On some servers the public directory is "public_html" but others may be "htdocs". I don't want to hard code the name in my code, much better to get the correct name from the server. I can't figure out why "pwd" works but $_SERVER array and dirname do not.

I read the documentation at: https://www.php.net/manual/en/function.ssh2-exec.php There is no place that they describe which PHP commands are supported and which are not supported.

Can someone please explain what I might be doing wrong or what I am missing?

//$stream = ssh2_exec($connection, "pwd;"); // This command works returns /home/username
//$stream = ssh2_exec($connection, "dirname(__DIR__);"); // returns null
$stream = ssh2_exec($connection, "$_SERVER['DOCUMENT_ROOT'];"); // Returns error "Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING)..."

stream_set_blocking( $stream, true );
$remotePublicDirectory = "";
while( $buffer = fread($stream,4096) ){
    $remotePublicDirectory .= $buffer;
}
fclose($stream);
$remotePublicDirectory = trim($remotePublicDirectory);
echo '$remotePublicDirectory = ' . $remotePublicDirectory . '<br/>';
Jim Dandy BOA
  • 533
  • 7
  • 13
  • `ssh2_exec` runs a remote terminal, not a remote `php`. So if you want to execute php code you need to use the php binary, like `ssh2_exec($connection, '/usr/local/bin/php echo $_SERVER["DOCUMENT_ROOT"];');`. – Andrea Olivato Mar 16 '22 at 06:01
  • Furthermore, the `php` binary has no idea what your document root is. Because it's run from command line, not from the webserver. So `$_SERVER['DOCUMENT_ROOT']` will not be defined and `dirname` will also not be useful – Andrea Olivato Mar 16 '22 at 06:02
  • If you want to know the server root, you need to access and read your webserver configuration (e.g. /etc/nginx/conf.d/server.conf) – Andrea Olivato Mar 16 '22 at 06:02
  • Thank you, that makes it very clear. I guess I will have to hard code it after all because I have a Bluehost account which does not give access to the /etc/nginx/conf.d/server.conf file. – Jim Dandy BOA Mar 16 '22 at 13:49
  • If you're simply trying to get your webserver root path, you can use `__DIR__`. You can use your config file (or a file you include everywhere in your project) to define a constant variable containing `__DIR__`. For example `define('ROOT', __DIR__.'/');`. This way you'll have a `ROOT` constant that you can use everywhere in your project and that contains the absolute path to your web root – Andrea Olivato Mar 17 '22 at 00:37

0 Answers0