Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Xanger's avatar

Code overloads the server

In my Laravel project when I load an image it creates a record in the Media table, when I go to retrieve it in an article I use the shortcode:

[image id="" p="right" s="medium"]

And to convert the shortcode to the html tag I use a Parser, here it is:


    public function parseContent($content)
    {
      
        $patterns = [
            'image' => '/\[image id="(.*?)"(?: p="(.*?)" s="(.*?)")?\]/',
        ];

        foreach ($patterns as $name => $pattern) {
            $content = preg_replace_callback($pattern, function ($matches) use ($name) {
                $methodName = 'replace' . ucfirst($name);
                return method_exists($this, $methodName) ? $this->$methodName(...array_slice($matches, 1)) : $matches[0];
            }, $content);
        }

        return $content;
    }

    private function replaceImage($id, $align = null, $size = null)
    {
        $media = Media::find($id);

        if ($media) {
            $imgTag = '<a class="itemgallery" href="' . Storage::disk($media->disk)->url($media->path) . '"><img src="' . Storage::disk($media->disk)->url($media->path) . '"';
            
            if ($align) {
                $imgTag .= ' data-align="' . $align . '"';
            }

            if ($size) {
                $imgTag .= ' data-size="' . $size . '"';
            }

            $imgTag .= '></a>';

            return $imgTag;
        }

        return '[Error]';
    }

This is going to consume me so much server memory resources. going from 500MB even to 4GB.... Do you have any ideas?

0 likes
2 replies
jlrdw's avatar

Make sure images are optimized for the web.

Xanger's avatar

@jlrdw The overload I have since I adopted the method in the shortcode. To avoid the hardcoded I currently have, So it's a matter of code...

Please or to participate in this conversation.