PHP图像上传内存限制减少

时间:2017-02-01 17:48:35

标签: php memory-leaks image-uploading image-upload

我使用PHP文件从我的Web应用程序将图像上传到我的服务器,并且最近遇到了一些内存限制问题,我希望有比我更多经验的人可以提供帮助。上传的大部分图片都来自手机,因此文件大小非常易于管理,但最近有一些来自单反相机的上传导致了这些问题。这些图像的大小约为7-8MB,我假设我们的PHP内存限制为64MB可以处理这个问题。经过检查,我发现我们的crop函数中的imagecreatefromjpeg()函数是罪魁祸首,尽管我假设在此之前已经填充了内存,尽管使用imagedestroy()来清除以前创建的任何图像。在使用ini_set('memory_limit')将限制提升到更高的值后,我发现脚本按预期工作,但我更喜欢更清洁的解决方案。我已经附上了下面的代码,我们将非常感谢任何帮助。

ini_set('memory_limit', '256M');

if(isset($_POST)) {
    ############ Edit settings ##############
    $ThumbSquareSize        = 200; //Thumbnail will be 200x200
    $ThumbPrefix            = "thumbs/"; //Normal thumb Prefix
    $DestinationDirectory   = '../../../uploads/general/'; //specify upload directory ends with / (slash)
    $PortfolioDirectory   = '../../../images/portfolio/';
    $Quality                = 100; //jpeg quality
    ##########################################

    $imID = intval($_POST['imageID']);
    $image = $_POST['image'];
    $data = $image['data'];
    $name = $image['name']; //get image name
    $width = $image['width']; // get original image width
    $height = $image['height'];// orig height
    $type = $image['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
    $desc = $image['desc'];
    $album = intval($image['album']);
    $customer = intval($image['customer']);
    $tags = $image['tags'];
    $allTags = $_POST['allTags'];
    $portType = intval($image['portType']);
    $rating = intval($image['rating']);
    $imData = array();

    if(strlen($data) < 500) {
        $dParts = explode('?', $data);
        $path = $dParts[0];
        $base64 = file_get_contents($path);
        $data = 'data:' . $type . ';base64,' . base64_encode($base64);
    }

    function base64_to_jpeg($base64_string, $output_file) {
        $ifp = fopen($output_file, "wb");

        $data = explode(',', $base64_string);

        fwrite($ifp, base64_decode($data[1]));
        fclose($ifp);

        return $output_file;
    }

    function base64_to_png($base64_string, $output_file) {

        $img = str_replace('data:image/png;base64,', '', $base64_string);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);

        $im = imagecreatefromstring($data);
        if ($im !== false) {
            imagepng($im, $output_file);
            imagedestroy($im);
        }

        return $output_file;
    }


   if($stmt = $db -> prepare("UPDATE `images` SET name = ?, type = ?, description = ?, width = ?, height = ?, rating = ?, portType = ?, customer = ?, album = ?, dateModified = NOW() WHERE ID = ?")) {


      $stmt -> bind_param("sssiiiiiii", $name, $type, $desc, $width, $height, $rating, $portType, $customer, $album, $imID);

        if (!$stmt->execute()) {
            echo false;
        } else {


            $delTags = "DELETE FROM tagLink WHERE imageID = $imID";
            if(!$db->query($delTags)) {
                echo $db->error;
            }

            if(sizeof($tags) > 0) {
                foreach($tags as $tag) {
                    $tagQ = "INSERT INTO tagLink (imageID, tag) VALUES ($imID, '$tag')";
                    if(!$db->query($tagQ)) {
                        echo $db->error;
                    }
                }
            }

            switch(strtolower($type))
            {
                case 'png':
                    $fname = $name . '(' . $imID . ').png';
                    $file = $DestinationDirectory . $fname;
                    $portfile = $PortfolioDirectory . $fname;
                    $thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
                    $CreatedImage = base64_to_png($data,$file);

                    break;
                case 'jpeg':
                case 'pjpeg':
                case 'jpeg':

                    $fname = $name . '(' . $imID . ').jpeg';
                    $file = $DestinationDirectory . $fname;
                    $portfile = $PortfolioDirectory . $fname;
                    $thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
                    $CreatedImage = base64_to_jpeg($data,$file);

                    break;
                default:
                    die('Unsupported File!'); //output error and exit
            }

            array_push($imData, $imID);
            array_push($imData, $name);
            array_push($imData, $type);
            array_push($imData, $portType);


            echo json_encode($imData);

            if(!cropImage($width,$height,$ThumbSquareSize,$thumbDest,$CreatedImage,$Quality,$type))
            {
                echo 'Error Creating thumbnail';
            }


        }

        $stmt -> close();


   } else {
     /* Error */
     printf("Prepared Statement Error: %s\n", $db->error);
   }

       /* Close connection */
   $db -> close();

    include '../cron/updatePortfolio.php';



}


//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$type)
{
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0)
    {
        return false;
    }

    if($CurWidth>$CurHeight)
    {
        $y_offset = 0;
        $x_offset = ($CurWidth - $CurHeight) / 2;
        $square_size    = $CurWidth - ($x_offset * 2);
    }else{
        $x_offset = 0;
        $y_offset = ($CurHeight - $CurWidth) / 2;
        $square_size = $CurHeight - ($y_offset * 2);
    }


    switch(strtolower($type))
    {
        case 'png':
        $imageX = imagecreatefrompng ( $SrcImage );
        break;
        case 'jpeg':
        case 'pjpeg':
        case 'jpeg':
        $imageX = imagecreatefromjpeg ( $SrcImage );
        break;
        default:
        return false;
    }



    $NewCanves  = imagecreatetruecolor($iSize, $iSize);
    if(imagecopyresampled($NewCanves, $imageX, 0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
    {
        switch(strtolower($type))
        {
            case 'png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'jpeg':
            case 'pjpeg':
            case 'jpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }

        if(is_resource($NewCanves)) {
            imagedestroy($NewCanves);
        }

        return true;

    }

}

1 个答案:

答案 0 :(得分:-1)

查看

中的php.ini
upload_max_filesize = 40M
post_max_size = 40M

将40M更改为最大尺寸