我对 PHP 有点陌生。
我有两个不同的主机,我希望其中一个的 php 页面向我显示另一个的目录列表。我知道如何在同一主机上使用 opendir() ,但是否可以使用它来访问另一台机器?
提前致谢
尝试:
<?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>";
您可以使用 PHP 的FTP 功能远程连接到服务器并获取目录列表:
// 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);
我无法让 FTP 建议正常工作,所以我采取了一种更非传统的方法,基本上它从“索引”页面中提取 html 并提取文件名。
索引页面:
提取码:
$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";
}
}