我想连接到一个远程FTP服务器,并将图像文件上传到该服务器的某个特定位置。我可以连接到服务器,但无法上传文件。
每次函数ftp_put()
返回 false 时。 我调试了很多代码,但我不明白我在哪里犯了错误。
以下是我的代码:
网页代码:
<form method="post" enctype="multipart/form-data" action="xyz.php">
<input type="file" name="student_image" id="student_image" />
</form>
PHP 代码(xyz.php):
$t = time();
$allowed_image_extension = array("jpg","jpeg","gif","png","JPG","JPEG","GIF","PNG");
if(!empty($_FILES['student_image']['name'])) {
$ext = pathinfo($_FILES['student_image']['name'], PATHINFO_EXTENSION);
$student_image_name = 'student_'.$t.'.'.$ext;
$_POST['student_name'] = $student_image_name;
$ftp_server="52.237.5.85";
$ftp_user_name="myservercreds";
$ftp_user_pass="MyServerCreds";
$file = $_FILES['student_image']['name'];//tobe uploaded
$remote_file = "/Students/".$_POST['student_name'];
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file'n";
exit;
} else {
echo "There was a problem while uploading $file'n";
exit;
}
// close the connection
ftp_close($conn_id);
}
在调试期间,除了函数ftp_put()
中的一个地方之外,我在任何地方都获得了 True 和资源。
我相信
这可能是由于您将绝对路径作为 $remote_file 传递。ftp_put失败应该意味着无论出于何种原因,您都无法写入该位置。我相信更改此设置以使它在路径之前没有/应该可以解决问题(请注意,该文件将相对于 ftp 用户的 home dir,这通常是您通过 ftp 连接时首次显示的目录)。
这应该看起来像这样:
$file = $_FILES['student_image']['tmp_name'];
$remote_file = "Students/".$_POST['student_name'];
编辑:编辑答案以包括tmp_name而不是名称,这是一个两部分。
您使用了错误的文件名:
$file = $_FILES['student_image']['name'];//tobe uploaded
^^^^^^^^
这是用户计算机上文件的文件名。PHP 不使用它。它将上传放入随机文件名中,并将该名称存储在['tmp_name']
中。你想要
$file = $_FILES['student_image']['tmp_name'];
相反。由于您使用了错误的文件名,服务器上不存在的文件,ftp_put正确返回 false,因为无法读取该不存在的文件。
你为什么不尝试获取ftp错误:
$trackErrors = ini_get('track_errors');
ini_set('track_errors', 1);
if (!@ftp_put($my_ftp_conn_id, $tmpRemoteFileName, $localFileName, FTP_BINARY)) {
// error message is now in $php_errormsg
$msg = $php_errormsg;
ini_set('track_errors', $trackErrors);
throw new Exception($msg);
}
@ref:使用PHP时如何获得FTP错误