使用file_get_contents和ftp_put

时间:2011-09-12 09:58:29

标签: php

有没有办法可以使用file_get_contents然后ftp文件将从file_get_contents获取的文件上传到远程站点?

我有以下代码,但我收到错误:

<?php
ob_start();

$file = 'http://test4.*****.com/';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";


$host = 'ftp.******.com';
$usr = '*******';
$pwd = '*******';        
$local_file = $current;
$ftp_path = 'test4/resources-test.php';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");     

ftp_pasv($conn_id, true);
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// perform file upload
ftp_chdir($conn_id, '/public_html/');
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
// close the FTP stream
ftp_close($conn_id);

ob_end_flush();

?>

以下是我得到的所有错误:

Warning: ftp_put(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

此后切断了......

1 个答案:

答案 0 :(得分:4)

ftp_put期望本地文件的路径作为其第三个参数,而不是文件的内容,就像您在此处传递它一样:

$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";

...

$local_file = $current;

...

$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);

你可能想要做这样的事情:

$fp = fopen('php://temp', 'r+');
fputs($fp, $current);
rewind($fp); // so that we can read what we just wrote in

// Using ftp_fput instead of ftp_put -- also, FTP_ASCII sounds like a bad idea
$upload = ftp_fput($conn_id, $ftp_path, $fp, FTP_BINARY);
fclose($fp); // we don't need it anymore