Skip to content

[server-side] Memory limit utilities #4

@Mark-H

Description

@Mark-H

Some extras (MoreGallery and ContentBlocks) deal with resizing images, which can sometimes cause issues if the memory limit is too low. Perhaps some of those utils could go into Alpacka.

    /**
     * @return int|string
     */
    private function _getMemoryLimit()
    {
        try {
            $limit = @ini_get('memory_limit');
            if ( is_numeric( $limit ) ) {
                $memoryLimit = $limit;
            } else {
                $value_length = strlen( $limit );
                $qty = substr( $limit, 0, $value_length - 1 );
                $unit = strtolower( substr( $limit, $value_length - 1 ) );
                switch ( $unit ) {
                    case 'k':
                        $qty *= 1024;
                        break;
                    case 'm':
                        $qty *= 1048576;
                        break;
                    case 'g':
                        $qty *= 1073741824;
                        break;
                }
                $memoryLimit = $qty;
            }
        }
        catch (Exception $e) {
            // Pretend nothing happened and assume 24M
            $memoryLimit = 24 * 1048576;
        }

        return $memoryLimit;
    }

    public function setMemoryLimit()
    {
        if ($this->_memoryLimitIncreased) return;
        $before = ini_get('memory_limit');
        $unit = strtoupper(substr($before, -1));
        $number = substr($before, 0, -1);
        $newLimit = $this->getOption('moregallery.upload_memory_limit', null, '256M');
        $newLimitNumber = substr($newLimit, 0, -1);
        if ($unit !== 'G' && $number < $newLimitNumber) {
            @ini_set('memory_limit', $newLimit);
            $after = ini_get('memory_limit');

            if ($before === $after) {
                $this->modx->log(modX::LOG_LEVEL_ERROR,
                    '[moregallery] Attempted to up the memory limit from ' . $before . ' to ' . $newLimit . ', but failed. You may run out of memory while resizing the uploaded image.');
            }
        }
        $this->_memoryLimitIncreased = true;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions