【问题标题】:PHP read remote file through FTP connectionPHP通过FTP连接读取远程文件
【发布时间】:2018-11-17 02:27:22
【问题描述】:

我有简单的代码将数据从 txt 文件加载到 mysql,它运行良好,但我的最后一个问题是我的文件在 ftp 服务器上而不是在本地文件夹中。 下面是我的代码如何重写这一行以使用凭据连接到我在 ftp (test.txt) 上的文件?

$open=fopen('test.txt','r');

$conn = mysqli_connect('localhost','user','password','db_name');

if(!$conn)
{
    die(mysqli_error());
}

$query = mysqli_query($conn, "DELETE FROM test");

$open = fopen('test.txt','r');

fgets($open);
fgets($open);
while (!feof($open)) 
{
  $getTextLine = fgets($open);
  $explodeLine = explode("|",$getTextLine);

  list($Login,$Inday,$Start_przerwy,$Koniec_przerwy,$Czas_przerwy,$Odcinek) = $explodeLine;

  $qry = "insert into test (Login,Inday,Start_przerwy,Koniec_przerwy,Czas_przerwy,Odcinek) values('".$Login."','".$Inday."','".$Start_przerwy."','".$Koniec_przerwy."','".$Czas_przerwy."','".$Odcinek."')";
  mysqli_query($conn,$qry);
}
fclose($open);
echo "done";

【问题讨论】:

  • 您可能需要考虑编写一个shell 脚本,然后让PHP 执行该shell 脚本。你甚至可以将变量传递给它。
  • 这是对(sql)注入开放的;如果您不希望您的数据库有一天突然消失,请使用准备好的语句。

标签: php ftp


【解决方案1】:

简单相同,但定义协议ftp://usernamepassword

$file = "ftp://username:pa‌​ssword@hostname/path/to/test.txt";
$open = fopen($file, "r");

或:

$file = "ftp://username:pa‌​ssword@hostname/path/to/test.txt";
$lines = explode("\n", file_get_contents($file));

foreach($lines AS $line) {
  $line = trim($line);
  // body of while
}


不需要ftp_*methods,保持简单(:

【讨论】: