Geoff
Geoff

Reputation: 6639

Error in uploading files in yii2 move_upload function

Am doing multiple file upload in the controller but the file doesn't get uploaded controller code: for the upload

$images = $_FILES['evidence'];
$success = null;

$paths= ['uploads'];

// get file names
$filenames = $images['name'];


// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
    $success = true;
    $paths[] = $target;
} else {
    $success = false;

    break;
}

echo $success;
}
// check and process based on successful status 
if ($success === true) {
        $evidence = new Evidence();
        $evidence->case_ref=$id;
        $evidence->saved_on=date("Y-m-d");
        $evidence->save();

$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];

foreach ($paths as $file) {
    unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}

//  return a json encoded response for plugin to process successfully
echo json_encode($output);

I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file

Upvotes: 2

Views: 468

Answers (2)

Fabrizio Caldarelli
Fabrizio Caldarelli

Reputation: 3008

Have you added enctype attribute to form tag?

For example:

 <form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form> 

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133360

Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...

The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?

this is the related php man php.net/manual/en/function.move-uploaded-file.php

Upvotes: 2

Related Questions