попробуйте catch блок не перехватывает исключение в коде - PullRequest
0 голосов
/ 29 июня 2019

У меня есть следующий фрагмент кода, который загружает изображение и поворачивает его в зависимости от ориентации, а также выполняет некоторые базовые проверки типов файлов.

Но я заметил, что если я переименую файл с расширением скажем .jpg, он будет принят и выдаст ошибку, когда я нажму exif_read_data ОШИБКА: exif_read_data (5d17a444d54694.60141039.jpg): файл не поддерживается, что идеально хорошо, так как я непреднамеренно хочу, чтобы это произошло, чтобы остановить загрузку файла не-imagetype.

Итак, я решил попробовать блок catch по этому поводу, чтобы выдать ошибку, если здесь произошла ошибка, тогда я мог удалить загруженный файл.

но блок try catch не перехватывает ошибку, и я не понимаю, почему.

Есть идеи, как мне добиться этого, чтобы достичь того, что мне нужно?

 if(isset($_FILES['file'])){

    $file = $_FILES['file'];

    $file_name = $_FILES['file']['name'];
    $file_tmp_name = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_error = $_FILES['file']['error'];
    $file_type = $_FILES['file']['type'];




    $file_ext = explode('.', $file_name);
    $file_actual_ext = strtolower(end($file_ext));

    $allowed = array('jpg', 'jpeg', 'png');

    if (in_array($file_actual_ext, $allowed)) {
        if ($file_error === 0) {
            if ($file_size < 6000000) {

                $site_path = '/GunStalker-Website-Forms/Examples/login real/advert_image_uploads/';
                $file_name_new = uniqid('', true) . "." . $file_actual_ext;
                $root = $_SERVER['DOCUMENT_ROOT'];
                $file_destination = $root . $site_path . $file_name_new;
                move_uploaded_file($file_tmp_name, $file_destination);

                try{
                if ($file_actual_ext != 'jpg' && $file_actual_ext != 'jpeg' ){
                convertToJpeg($file_destination, $file_destination, $quality = 100);
                }

                $exif_data = exif_read_data($file_destination );
                $orientation = orientation($exif_data);
                $degree = orientation_rotate($orientation);

                $image_data = imagecreatefromjpeg($file_destination);
                $image_rotate = imagerotate($image_data,$degree,0 );
                imagejpeg($image_rotate, $file_destination);
                imagedestroy($image_rotate);
                imagedestroy($image_data);

                $primary_flag = null; //Testing 
                $file_destination = $site_path . $file_name_new;

                include 'advert_new_gun_save_image_script.inc.php';
            }
            catch (\Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "\n";
            }

                include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';




                   //<input type="submit" name="submitimage" id="submitimage" value="'. $getadvertimages_row['image_id'] . '" text="X" class="remove-image" style="display: inline;" >


            } else {
                echo "Error Uploading File this is too large";
                include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
            }

        } else {
            echo "Error Uploading File";
            include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
        }

    } else {
        echo "You cannot do this";
        include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
    }
    // File upload configuration
    }
    else{
        echo "Error Please Check File";
        include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
    }

1 Ответ

0 голосов
/ 29 июня 2019

Мне пришлось установить set_error_handler() и класс ErrorException, чтобы превратить все ошибки php в исключения.Нашел по другому вопросу

set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
...