Imagick error: ‘unable to open image’ image upload

image-uploadingimagick

I get the following error when trying to process uploaded images with imagick.

Fatal error: Uncaught exception 'ImagickException' with message 'unable to open image `9eK59iu.jpg': No such file or directory @ error/blob.c/OpenBlob/2644' in D:\PATH\upload.php on line 77

The code looks like this:

<?php

    $new_folder_name = "D:/PATH/content";       
    mkdir("$new_folder_name",0700);

    $tmp_img = $_FILES["upload_file"]["tmp_name"];

    $img = new Imagick($tmp_img);
    $img->thumbnailImage(100 , 100 , TRUE);
    $img->writeImage($new_folder_name);

?>

Without imagick the image upload works just fine.

Only imagick won't open the image given to $_FILES

I also tried to open the image with imagick, after move_uploaded_file, like this:

<?php

    $extension = pathinfo($upload_file_name, PATHINFO_EXTENSION);
    $new_upload_file_name = rand(00000, 99999).".".$extension;

    $new_folder_name = "D:/PATH/content".time();        
    mkdir("$new_folder_name",0700);

    $path_to_file = $new_folder_name."/".$new_upload_file_name;

    move_uploaded_file($_FILES["upload_file"]["tmp_name"],$path_to_file);

    $img = new Imagick($path_to_file);
    $img->thumbnailImage(100 , 100 , TRUE);
    $img->writeImage($new_folder_name);

?>

neither works.. 🙁

Any suggestion?

Best Solution

Read the file upload docs. The server-side temporary filename assigned by PHP to store the uploaded file in ['tmp_name'] in the $_FILES array. You're trying to use the client-side user-provided ['name'], which DOES NOT exist anywhere on your server.

$tmp_img = $_FILES["upload_file"]["tmp_name"];
                                   ^^^^

You are also simply assuming that the upload has succeed. That is NOT a good thing. Never EVER assume success with dealing with remote resources (web apis, file uploads, database operations, etc...). ALWAYS check for errors:

if ($_FILES['upload_file']['error'] !== UPLOAD_ERR_OK) {
  die("Upload failed with error code " . $_FILES['upload_file']['error']);
}
Related Question