Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 allocates uploaded file to memory

While uploading a file bigger than post_max_size in Symfony, the uploaded file is allocated in the memory.

Fatal error: Allowed memory size of 150994944 bytes exhausted (tried to allocate 84627994 bytes) in /Applications/MAMP/htdocs/Symfony/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/DataCollector.php on line 28

Why is symfony trying to allocate a file to the memory on POST?

1/ php.ini

file_uploads = On
upload_tmp_dir = /Applications/MAMP/tmp/php
upload_max_filesize = 32M
post_max_size = 48M

2/ THE CONTROLLER

<?php
//AcmeDemoBundle/Controller/DemoController
namespace Acme\DemoBundle\Controller;
use Symfony\Component\HttpFoundation\Request;

class DemoController extends Controller
{

public function createAction(Request $request)
{

    if ($request->getMethod() == 'POST')
    {
        if ($_FILES["file"]["size"] < 3000000 )//3Mb
        {
            if ($_FILES["file"]["error"] > 0)
            {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
            }
            else
            {
                if (empty($_POST) && empty($_FILES) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post')
                {
                    echo "The file is bigger than post_max_size in php.ini.";
                }
                else
                {
                    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

                    if (file_exists("upload/" . $_FILES["file"]["name"]))
                    {
                        echo $_FILES["file"]["name"] . " already exists. ";
                    }
                    else
                    {
                        move_uploaded_file($_FILES["file"]["tmp_name"],
                            "upload/" . $_FILES["file"]["name"]);
                        echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
                    }
                }
            }
        }
        else
        {
            echo "Invalid file";
        }

    }

    return $this->container->get('templating')->renderResponse('AcmeDemoBundle:Demo:create.html.twig');

}

3/ THE TEMPLATE

//AcmeDemoBundle/Resources/views/Demo/create.html.twig
{% extends "AcmeDemoBundle::layout.html.twig" %}

{% block content %}

<h1>Upload File</h1>

<form action="#" method="post"
      enctype="multipart/form-data">
    <label name="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
</form>

{% endblock %}
like image 708
Mick Avatar asked Dec 20 '22 20:12

Mick


1 Answers

I assume that you're trying symfony via the app_dev.php front controller.

By default, in the dev environment, the profiler is enabled for every requests.

framework:
    profiler: { only_exceptions: false }

Just change the only_exceptions param from false to true, and try again.

framework: profiler: { only_exceptions: true }

You should use the tools that the framework provides you to handle file upload.

Action:

public function createAction(Request $request)
{
    $form = $this->createFormBuilder()
        ->add('attachment', 'file')
        ->getForm();

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            $file = $form['attachment']->getData(); /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */

            echo $file->getClientSize();
        }
    }

    return $this->render('AcmeDemoBundle:Demo:create.html.twig', array(
        'form' => $form->createView(),
    ));
}

Template:

{% extends "AcmeDemoBundle::layout.html.twig" %}

{% block content %}

<h1>Upload File</h1>

<form action="" method="post" {{ form_enctype(form) }}>
    {{ form_errors(form) }}

    {{ form_row(form.attachment) }}

    {{ form_rest(form) }}

    <input type="submit" />
</form>

{% endblock %}

With this code, php never exceeds memory usage. If the file is too big, the form show an error, and the code inside "if ($form->isValid())" is not executed.

Have a look at the form documentation : http://symfony.com/doc/current/book/forms.html and the reference for the "file" field type : http://symfony.com/doc/current/reference/forms/types/file.html

like image 67
AdrienBrault Avatar answered Dec 26 '22 15:12

AdrienBrault