Why the image is getting corrupted uploaded to the FTP server using PHP? [duplicate]

旧街凉风 提交于 2019-12-18 05:07:52

问题


I'm uploading image to the FTP server at specific folder location. The code is working fine. But when I look at the uploaded image, I got corrupted image file which can't be opened. For few image files the image in a file gets corrupted. I'm not understanding why this is happening.

Following is the workable code that I tried:

      if(!empty($_FILES['student_image']['name'])) {
        $ext = pathinfo($_FILES['student_image']['name'], PATHINFO_EXTENSION);     

        $student_image_name = 'student_'.$student_data['student_id'].'.'.$ext;

        $ftp_server="56.215.30.91"; 
        $ftp_user_name="myservercreds"; 
        $ftp_user_pass="MyServerCreds";

        $file = $_FILES['student_image']['tmp_name'];//file to be uploaded to FTP server 
        $remote_file = "/Students/".$student_image_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);

        if($login_result) {
          if(!is_dir('ftp://myservercreds:MyServerCreds@56.215.30.91/Students')) {
            ftp_mkdir($conn_id, "/Students");
            ftp_chmod($conn_id, 0777, '/Students');
          }

          if(!file_exists("/Students/".$student_image_name))
            $file_upload_status = ftp_put($conn_id, $remote_file, $file, FTP_ASCII);                    
        }  

    // close the connection 
    ftp_close($conn_id);
  }

I'm not understanding when does the image file is getting corrupt while uploading to the FTP server of after finishing the upload.


回答1:


You should set the mode with ftp_put to be FTP_BINARY:

ftp_put($conn_id, $remote_file, $file, FTP_BINARY); 

This is mandatory since ASCII mode checks whether the line endings differ on client/server (your case, since you are likely on windows and the server runs unix) and tries to convert them (\r\n\n). In BINARY mode files are being sent as is.



来源:https://stackoverflow.com/questions/27266311/why-the-image-is-getting-corrupted-uploaded-to-the-ftp-server-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!