Wilf
Wilf

Reputation: 2315

Cannot upload file with custom php function

I try using function to upload different kind of file by giving it variables. As shown below:

<?
function fn_fileUpload($data,$dir,$uid){
    include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
    if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
        $fileTmpPath = $data['tmp_name'];
        $fileName = $data['name'];
        $fileSize = $data['size'];
        $fileType = $data['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExt = strtolower(end($fileNameCmps));
        $newFileName = $uid . '.' . $fileExt;
        //check file ext
        $okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
        if (in_array($fileExt, $okEXT)) {
            $fileDir = '/'.$dir.'/';
            $dest_path = $fileDir.$newFileName;          
            if(move_uploaded_file($fileTmpPath, $dest_path)){
                try{
                    $stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
                    $stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
                    $stmt2->execute();
                    $result = 'ok';
                }catch(mysqli_sql_exception $err){
                    $result=$err;
                }
            }else{
              $result = 'Cannot upload file!';
            }
        }//in_array
    }//if(isset
    return $result;
}
?>

And this is how to use:

//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);

From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).

The db went through correctly. Is there any idea how to fix this?

Upvotes: 0

Views: 54

Answers (1)

Fatemeh Gharri
Fatemeh Gharri

Reputation: 397

You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.

Upvotes: 1

Related Questions