Example #1
0
 public function updateProfileImage(Request $request, Response $response, array $args)
 {
     /* Directory to move the file to once processed */
     $destination = __DIR__ . "../../../../../images/";
     /* The uploaded file */
     /** @var $file UploadedFile */
     $file = $request->getUploadedFiles()['image'];
     /* If there is an error in the file, stop upload */
     if ($file->getError() != UPLOAD_ERR_OK) {
         return "Upload failed";
     }
     $currentLocation = $file->file;
     /* If the file is not a jpg, png, or gif, stop upload */
     $finfo = new \finfo(FILEINFO_MIME_TYPE);
     if (false === ($ext = array_search($finfo->file($currentLocation), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true))) {
         return "Invalid File Format. Only .jpg, .gif, and .png accepted.";
     }
     $size = getimagesize($currentLocation);
     /* If the file is greater than 2MB in size, stop upload. */
     if ($size > 1024 * 1024 * 2) {
         return "Upload failed. Image is greater than 2MB.";
     }
     $givenName = $file->getClientFilename();
     /* Generate a unique name for this file from its SHA1 hash. */
     $fileHashName = sha1_file($currentLocation);
     /* Build the full path and extension of the file */
     $fullFilePath = $destination . $fileHashName . $ext;
     /* Replace uploaded file with recreated image and save */
     switch ($ext) {
         case 'jpg':
             $image = imagecreatefromjpeg($currentLocation);
             imagejpeg($image, $fullFilePath);
             break;
         case 'gif':
             $image = imagecreatefromgif($currentLocation);
             imagegif($image, $fullFilePath);
             break;
         case 'png':
             $image = imagecreatefrompng($currentLocation);
             imagealphablending($image, true);
             imagesavealpha($image, true);
             imagepng($image, $fullFilePath);
             break;
     }
     /* Remove original upload */
     unlink($currentLocation);
     /* Get user from route args */
     $user = $args['user'];
     /* Make change in Database */
     if ($this->dbService->updateUserImage($user['username'], $fullFilePath, $givenName, $size)) {
         return "Upload successful";
     } else {
         return "Upload failed";
     }
 }