网络文件的路径

时间:2011-06-30 19:27:17

标签: php networking file-copying

我的网络服务器在一台服务器上运行,数据提取正在另一台服务器上运行。我的代码将尝试复制远程文件并将其存储在本地路径中。远程位置例如是/home/testUser/remoteData.xml。我知道服务器的IP地址和主机名。如何构建填充remotePath的路径?

#remotePath is the path to the file on the network
public function __construct()
{
   $this->localPath="currentData.xml";
   $this->remotePath="a remote path";
}

#this will attempt to make a copy from that network file and store it locally
private function fetchServer()
{
   if (!(file_exists($this->remotePath)) || (time() - filectime($this->remotePath)) >= 1200)
      return false;
   else
   {  $success = copy($this->remotePath, $this->localPath);
      if($success)
         return true;
      else
         return false;
   }
}

非常感谢!

3 个答案:

答案 0 :(得分:1)

如果您正在使用HTTP和PHP,则启用allow_url_fopen指令,您可以直接使用URL作为您的文件。例如:

$content = file_get_contents('http://www.yourdomain.dom/virtual/path/to-your-file');

/virtual/path/to-your-file是文档根目录的相对路径。

如果您的受限PHP环境不允许打开远程文件,则可以使用PHP cURL或PHP streams

编辑:

要将文件内容保存到本地文件,请使用file_get_contents():file_put_contents()的对应项。例如:

file_put_contents('path/to/the/local-file', $content);

答案 1 :(得分:1)

如果您使用的是HTTP,则无法检查创建时间。如果您知道它是一个小的,可管理的文件,您可以使用file_get_contents:

 $fl = @file_get_contents( '<stream>' );
 if( !$fl ) return false; // file does not exist remotely
 $ret = @file_put_contents( '<output name>', $fl );// just output it
 return $ret && true; //force it to boolean

如果它有点大,你可以使用cURL和流语法,或者你可以做类似于我上面做的事情:

 $fl = @fopen( '<stream>' );
 if( !$fl ) return false;// file does not exist remotely
 $out = @fopen( '<local file>', 'w');
 if( !$out ) return false;
 while($data = fread($fl)){fwrite($out,$data);}
 fclose($out);
 return true;

当然,在所有情况下,您必须将文件下载到本地版本,然后执行某种形式的校验和以查看是否存在差异。

修改


您刚才提到时间戳是一项要求,但您也有SSH。如果你有SSH,那么你可能可以使用SFTP(这是一种背负SSH的东西)。我已经将phpseclib用于了几个项目,虽然并不完美(它在PHP4中并且它并不真正为SSH提供隧道),但它仍然是一个非常令人印象深刻的库。看一下手册的networking部分(如果我记得的话)它会给你足够的东西来做你想要的。

答案 2 :(得分:0)

我不太确定我是否理解你的问题,但是如果你的远程位置是

http://www.somehost.com/home/testUser/remoteData.xml

那么这正是你的道路。如果您想通过HTTP获取源代码,则必须以http://开头。如果您希望通过FTP获取它,请使用ftp://。这将指示copy()函数启动适当的协议

编辑:关于filectime()这是一个文件系统功能,不适用于HTTP或FTP。如果您是源文件的作者,则可以在标题中设置一些日期时间信息。