在php上通过ftp_put上传后文件被破坏了

时间:2013-04-08 08:55:12

标签: php file-upload

我在服务器上通过php中的ftp_put上传任何文件后,文件上传但文件在服务器上损坏。

以下代码用于上传文件。

<html>
<body>

    <form action="upload.php" method="post"
          enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
    </form>

</body>
</html>

<?php
if (isset($_REQUEST['submit'])) {
    $local_file = $_FILES["file"]["tmp_name"];
    $ftp_path = 'path/newfolder';
    $filename = $_FILES["file"]["name"];
    $usr = 'userid';
    $pwd = 'password';
    $host = 'server_ip';
    $conn_id = ftp_connect($host, 21) or die("Cannot connect to host");
    ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
    $upload = ftp_put($conn_id, $ftp_path . '/' . $filename, $local_file, FTP_BINARY);
    print (!$upload) ? 'Cannot upload' : 'Upload complete';
}
}
?>

我尝试了jpeg,xls等...但我无法在上传后打开这些文件。

1 个答案:

答案 0 :(得分:0)

不确定可能导致该问题的原因,但假设您需要在move_uploaded_file之后尝试上传文件:

$filename = $_FILES["file"]["name"];    
$local_file = "some/tmp/storage/path/$filename";
if(move_uploaded_file($_FILES["file"]["tmp_name"], $local_file)) {
   $ftp_path = 'path/newfolder';
   $usr = 'userid';
   $pwd = 'password';
   $host = 'server_ip';
   $conn_id = ftp_connect($host, 21) or die("Cannot connect to host");
   ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
   $upload = ftp_put($conn_id, $ftp_path . '/' . $filename, $local_file, FTP_BINARY);
   print (!$upload) ? 'Cannot upload' : 'Upload complete';
   ulink($local_file); //remove temporary local file
} else {
   echo 'File upload error';
}

此外,通过选中$_FILES["file"]["error"]确保确实上传了文件。它应该等于UPLOAD_ERR_OK(其他错误codes