Search code examples
phprestfileslim

Multiple file upload slim framework only runs once


I'm trying to upload multiple files and save their path to a database using the slim framework. The problem is that when I test the code using postman, it uploads just one file and saves only that file to the database. (I'm using multifileupload[] as the key and file type to upload two or more files with one input.)

My code is below:

$app->post('/uploadfile',function(Request $request, Response $response, array $args) {
  $decodedsenttoke = $request->getAttribute('decoded_token_data');
  $directory = $this->get('upload_directory');
  $uploadedFiles = $request->getUploadedFiles();

  foreach ($uploadedFiles['multifileupload'] as $uploadedFile) {
    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
      $pathOfUploadedFiles = "http://someaddress.com/uploads/";
      $filename = moveUploadedFile($directory, $uploadedFile);
      $pathOfUploadedFiles .= $filename;
      $input = $request->getParsedBody();
      $insertsql = "INSERT INTO files (picturelink   ,  picturetitle ,  appointid)"
        ."VALUES (:picturelink  , :picturetitle , :appointid )";
      $this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
      $sth = $this->db->prepare($insertsql);
      $sth->bindParam("picturelink", $pathOfUploadedFiles);
      $sth->bindParam("picturetitle", $input['picturetitle']);
      $sth->bindParam("appointid", $input['appointid']);
      $sth->execute();
      $insertArray = array('message'=>'inserted');

      return $this->response->withJson($insertArray);
    }
  }
});

Solution

  • You have

    return $this->response->withJson($insertArray);
    

    at the end of the inside of the if inside the loop - this will automatically exit the code and return the content after the first file has uploaded.

    Move this to the end when all files have been uploaded.