What's wrong with the PHP script?



  • function compress_png($path_to_png_file, $max_quality = 90)
    {
        if (!file_exists($path_to_png_file)) {
            throw new Exception("File does not exist: $path_to_png_file"); // ругается на эту строку
        }
       $min_quality = 60;
       $compressed_png_content = shell_exec("/home/tmp/pngquant 2>&1 --quality=$min_quality-$max_quality - < ".escapeshellarg($path_to_png_file));
    
        if (!$compressed_png_content) {
            echo "0";
        }
    
    return $compressed_png_content;
    }
    

    I was working the code until yesterday, and suddenly I stopped working, the apache overloaded, the server overloaded and nothing.

    Fatal error: Uncaught exception 'Exception' with message 'File does not exist: ./pic/zombie-smashdown-dead-warrior481.png' in /home/admin/web/site.com/public_html/sql.php:10 Stack trace: #0 /home/admin/web/site.com/public_html/sql.php(122): compress_png('./pic/zombi...') #1 {main} thrown in /home/admin/web/site.com/public_html/sql.php on line 10
    

    And this is 122 lines:

    $path_to_uncompressed_file = './pic/'.p($_POST['title']).$rand_img.'.png';
    $path_to_compressed_file = './pic/'.p($POST['title']).''.$rand_img.'.png';
    file_put_contents($path_to_compressed_file, compress_png($path_to_uncompressed_file)); // 122 stkora
    unlink($path_to_uncompressed_file);



  • Add a file check ( http://php.net/manual/ru/function.file-exists.php before function file_put_contents():

    if (file_exists($path_to_uncompressed_file)) {
        file_put_contents($path_to_compressed_file, compress_png($path_to_uncompressed_file));
        unlink($path_to_uncompressed_file);
    }
    

    And don't resign to read mistakes and documentation. Otherwise you won't survive IT.

    UPD

    Didn't notice the code of the function. compress_png() at the beginning. You've got enough to catch. http://php.net/manual/ru/language.exceptions.php ♪ try{} catch(){}:

    $path_to_uncompressed_file = './pic/'.p($_POST['title']).$rand_img.'.png';
    $path_to_compressed_file = './pic/'.p($_POST['title']).'_'.$rand_img.'.png';
    try {
        file_put_contents($path_to_compressed_file, compress_png($path_to_uncompressed_file)); // 122 stkora
        unlink($path_to_uncompressed_file);
    } catch (\Exception $e) {
        // что-то пошло не так. Скорее всего файл не существует. Текст ошибки в $e->getMessage();
    }
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2