PHP - opendir on another server

柔情痞子 提交于 2019-11-28 06:20:23

问题


I'm kinda new to PHP.

I've got two different hosts and I want my php page in one of them to show me a directory listing of the other. I know how to work with opendir() on the same host but is it possible to use it to get access to another machine?

Thanks in advance


回答1:


You could use PHP's FTP Capabilities to remotely connect to the server and get a directory listing:

// set up basic connection
$conn_id = ftp_connect('otherserver.example.com'); 

// login with username and password
$login_result = ftp_login($conn_id, 'username', 'password'); 

// check connection
if ((!$conn_id) || (!$login_result)) { 
    echo "FTP connection has failed!";
    exit; 
}

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); 

// check upload status
if (!$upload) { 
    echo "FTP upload has failed!";
} else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
}

// Retrieve directory listing
$files = ftp_nlist($conn_id, '/remote_dir');

// close the FTP stream 
ftp_close($conn_id);



回答2:


Try:

<?php

$dir = opendir('ftp://user:pass@domain.tld/path/to/dir/');

while (($file = readdir($dir)) !== false) {
    if ($file[0] != ".") $str .= "\t<li>$file</li>\n";
}

closedir($dir);

echo "<ul>\n$str</ul>";



回答3:


I was unable to get the FTP suggestions to work so I took a more unconventional route, basically it yanks the html from the "Index of" page and extracts the filenames.

Index page:

Index of /files

  • Parent Directory
  • 1.jpg
  • 2.jpg
  • Extraction code:

        $dir = "http://www.yoursite.com/files/";
        $contents = file_get_contents($dir);
        $lines = explode("\n", $contents);
        foreach($lines as $line) {
            if($line[1] == "l") { // matches the <li> tag and skips 'Parent Directory'
                $line = preg_replace('/<[^<]+?>/', '', $line); // removes tags, curtousy of http://stackoverflow.com/users/154877/marcel
                echo trim($line) . "\n";
            }
        }
    


    来源:https://stackoverflow.com/questions/5292984/php-opendir-on-another-server

    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!