Search code examples
symfonysymfony-3.2php-7.2symfony3.x

Symfony 3.2 - HTTP 204 when echoing file_get_contents() for an image created with imagejpeg()


I created an image using the imagejpeg() function within my entity class

    $imageSize = $this->_getDefaultImageSize();

    $image = imagecreate($imageSize['width'], $imageSize['height']);
    imagecolorallocate($image, 54, 175, 105);

    header('Content-type: image/jpeg');

    imagejpeg($image, $path, null);

    imagedestroy($image);

Immediately after this, I return the file_get_contents($path) to my REST API Controller that echoes it with the corresponding header (e.g. 'Content-type: image/jpeg' ) based on the image extension that is persisted in the database.

If I send the generated file, it gives me a 204 header, no content. If I go in and rename the file and add a new image file downloaded from google with the same name as previously, it will send that image with a code 200. Delete the google image, rename the generated file back to normal and try getting it again, it returns a 204 again.

At first I thought it was a permission error in Linux, I gave the generated image 664 permission just like the google image and it still didn't work.

I also have to add that the image is being generated properly and can be viewed via the public directory on the server and via any image viewing application.

Any thoughts as to why an imagejpeg() generated image won't send on Symfony 3.2, using PHP 7.2?


Solution

  • To serve a file from your symfony application I suggest you take a look at the file function.

    This function should be available from your controller.

    This function take at first parameter a SplFileInfo object or the full path to the file. It add the good headers and the file content to the response.

    Example code from the controller

    public function fileAction()
    {
        // ....
    
        return $this->file($pathOrSplFileInfo, $fileNameForClientDownload);
    }