Search code examples
phpfile-uploadftpremote-serverfileserver

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


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.


Solution

  • 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.