Ask your Symfony questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Get contents of a file Symfony


I have a simple form with a file select box and submit button. All I need is for the user to select a text file with my form, click submit, and my code will verify the file is not harmful, and put the contents of the text file into a string. That's it. I don't need to store the file, I don't need to keep it, rename it, or move it. This shouldn't be that hard.

Answers (3)


Ben answers:

so what is the question? Or are you trying to get somebody to write that code for you for $1?


Florian Klein answers:

you'll need


Milena Dimitrova answers:

What is specific in your case is that you do not want to save the file at all. So, the action will look like this:

use Symfony\Component\HttpFoundation\File\UploadedFile;

public function uploadAction()
// ...

if ($form->isValid()) {

// instead of saving the file to the server
// $someNewFilename = ...
// $form['attachment']->getData()->move($dir, $someNewFilename);

// you just read the file contents as a string
$file = $form['attachment']->getData();
$extension = $file->guessExtension();
if ($extension == "txt") { // check if the file extension is as required; you can also check the mime type itself: $file->getMimeType()
$contents = file_get_contents($file->getPathname());
// do something with the file contents, e.g. store it to the database
// ...

// ...

// ...

Hope this helps.

jlvollmer comments:

Thank you, that is just what I was looking for. I was almost there.