使用php中的ftp将文件上传到服务器

时间:2015-11-13 10:28:41

标签: php android ftp server

我试图将图像上传到服务器但我没有访问该文件夹的权限,所以我使用了FTP连接。通过Android应用程序,我已经编码图像并将其发送到服务器。在服务器端,我只是解码它并尝试上传它。但我无法上传它。你能帮我解决这个问题。

 <?php
     // Get image string posted from Android App
     $base=$_REQUEST['image'];
     // Get file name posted from Android App
     $filename = $_REQUEST['filename'];
     // Decode Image
     $binary=base64_decode($base);
     header('Content-Type: bitmap; charset=utf-8');
    $ftp_server = "";
    $ftp_user_name = "";
    $ftp_user_pass = "";
    $destination_file = "/upload/images/".time().jpg";


    $conn_id = ftp_connect($ftp_server);
    ftp_pasv($conn_id, true); 

    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

    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,$conn_id";
    }

    $upload = ftp_put($conn_id, $destination_file,  $binary, FTP_BINARY);

    if (!$upload) { 
    echo "FTP upload has failed! $upload";
    } else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
    }
    ftp_close($conn_id);
    ?>

2 个答案:

答案 0 :(得分:0)

函数ftp_put的第三个参数需要一个文件名。您将图像二进制文件作为字符串传递。

更改行:

$upload = ftp_put($conn_id, $destination_file,  $binary, FTP_BINARY);

要:

$fileName = uniqid().'.jpg';
$filePath = '/tmp/'.$uniqid;
file_put_contents($filePath, $binary);

$upload = ftp_put($conn_id, $destination_file,  $filePath, FTP_BINARY);

答案 1 :(得分:0)

请添加ftp_pasv($ conn_id,true);成功登录后。然后这只会有效。