使用PHP将单个图像文件上载到FTP

时间:2013-09-10 11:54:52

标签: php html forms ftp

把头发拉出来。我想要做的就是有一个HTML表单然后PHP将所选文件上传到FTP服务器上的某个目录,但似乎没有任何工作正常。

这是html表单:

<form action="" enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input name="submit" type="submit" value="Upload File" />
</form>

这是下面的PHP(在同一个文件中):

<?php
$ftp_server = "myftp.co.uk";
$ftp_user_name = "myusername";
$ftp_user_pass = "mypass";
$destination_file = "/public_html/my/directory/";
$source_file = $_POST['file']['tmp_name'];

// set up basic connection
$conn_id = ftp_connect($ftp_server);
ftp_pasv($conn_id, true); 

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// check connection
if ((!$conn_id) || (!$login_result)) { 
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
    exit; 
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
}

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

// close the FTP stream 
ftp_close($conn_id);
?>

似乎连接到FTP ok,但没有上传 - 失败。我假设这与我处理要上传的文件的方式有关。?

此外,当我在这里时,如何设置作为变量上传的文件的名称?

2 个答案:

答案 0 :(得分:4)

在此处更改您的代码

$source_file = $_FILES['file']['tmp_name']; 

我已将$ _POST更改为$ _FILES ....

答案 1 :(得分:0)

上面的代码似乎很好,但FTP被动命令,即ftp_pasv($ conn_id,true); 应该在ftp_login之后,否则它将无法正常工作。 你可能会遇到这种错误: ftp_put():我不会打开到172.xx.xx.xx的连接(仅限xx.xxx.xxx.xxx)

<?php
$ftp_server = "your server or host";
$ftp_user_name = "username";
$ftp_user_pass = "password";
$ftp_port = "port";
$destination_file = "/public_html/my/directory/";
$source_file = $_FILES['file']['tmp_name'];

// set up basic connection
$conn_id = ftp_connect($ftp_server,$ftp_port);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 
// ftp passive cmd
ftp_pasv($conn_id, true);

// check connection
if ((!$conn_id) || (!$login_result)) { 
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
    exit; 
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
}

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

// close the FTP stream 
ftp_close($conn_id);
?>