【问题标题】:PHP - opendir on another serverPHP - 另一台服务器上的 opendir
【发布时间】:2011-07-14 15:50:26
【问题描述】:

我对 PHP 有点陌生。

我有两个不同的主机,我希望其中一个的 php 页面显示另一个的目录列表。我知道如何在同一主机上使用 opendir() ,但是否可以使用它来访问另一台机器?

提前致谢

【问题讨论】:

  • 没有抽象的“服务器”可以连接。您必须指定远程服务器支持并使用的某些协议

标签: php directory opendir


【解决方案1】:

我无法让 FTP 建议正常工作,所以我采取了一种更非传统的方法,基本上它从“索引”页面中提取 html 并提取文件名。

索引页:

/文件索引

  • Parent Directory
  • 1.jpg
  • 2.jpg
  • 提取码:

        $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";
            }
        }
    

    【讨论】:

      【解决方案2】:

      试试:

      <?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】:

        您可以使用 PHP 的 FTP Capabilities 远程连接到服务器并获取目录列表:

        // 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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多