Buy

All about Uploading Files in Symfony

0%
Buy

Setting up with the Symfony Local Web Server

Yo friends! It's file upload time! Woo! We are going to absolutely crush this topic... yea know... because file uploads are a critical part of the Internet. Where would we be if we couldn't upload selfies... or videos of Victor's cat... or SPAM our friends with memes!?!?! That's not a world I want to live in.

But... is uploading a file really that hard: add a file input to a form, submit, move the file onto your filesystem and... done! Meme unlocked! Well... that's true... until you start thinking about storing files in the cloud, like S3. Oh, and don't forget to add validation to make sure a user can't upload any file type - like an executable or PHP script! And you'll need to make sure the filename is unique so it doesn't overwrite other files... but also... it's kind of nice to keep the original filename... so it's not just some random hash if the user downloads it later. Oh, and once it's uploaded, we'll need a way to link to that file... except if you need to do a security check before letting the user download the file. Then you'll need to handle things in a totally different way.

Um... so wow! Things got complex! That's awesome! Because we're going to attack all of this... and more.

Downloading the Course Code

If you want to upload the maximum knowledge into your brain... you should definitely download the course code from this page and code along with me. After unzipping the file, you'll find a start/ directory that has the same code you see here. Open the README.md file for all the setup details... and a few extras.

The last setup step in our tutorials is usually to open a terminal, move into the project and run:

php bin/console server:run

to start the built in web server. You can totally do this. But, but, but! I want to show you a new tool that I'm loving: the Symfony local web server.

Downloading the Symfony Local Web Server

Find your browser and go to https://symfony.com/download. The Symfony local web server - or Symfony "client" - is a single, standalone file that is full of superpowers. At the top, you'll see instructions about how to download it. These steps are different depending on your operating system - but it should auto-select the right one.

For me, I'll copy this curl command, find my terminal, paste and enter! This downloaded a single executable file called symfony. To make sure I can type that command from anywhere, I'll move this into a global bin directory. By the way, you only need to do these steps once on your computer... so you're done forever!

Unless we've mucked things up, we should now be able to run this from anywhere: try it!

symfony

Say hello to the Symfony CLI! It lists the most popular commands, but there are a lot more - run:

symfony help

Woh. We'll talk more about this tool in another tutorial. But, to start a local web server, just say:

symfony serve

Ah. The first time you run this, you'll get an error about running: symfony server:ca:install. Let's do that:

symfony server:ca:install

You'll probably need to type in your admin password. This command installs a local SSL certificate authority... which is awesome because when we run symfony serve, it creates a local web server that supports https! Woh! We get free https locally! Sweet!

Find your browser and go to https://127.0.0.1:8000 - or localhost, it's the same thing. Say hello to The SpaceBar! This is the app we've been building in our Symfony 4 series: a news site for space-traveling friends from across the galaxy.

Try logging in with [email protected] and password engage. Then go to /admin/article.

This is the admin section for the articles on the site. Each article has an image... but until now, that image has basically been hardcoded. Click to edit one of the articles. Our first goal is clear: add a file upload field to this form so we can upload the article image, and then render that on the frontend.

But we're going to keep things simple to start... and take a deep and wonderful look into the fundamentals of how files are uploaded on the web and how that looks inside Symfony. Let's go!

Leave a comment!

  • 2019-05-06 weaverryan

    Hey Ricardo Gonçalves!

    Hmm, super weird! Good though to just reinstall from scratch - it indeed could have been some legitimate issue with the library :).

    Cheers!

  • 2019-04-30 Ricardo Gonçalves

    Hey Victor,

    Had the Symfony CLI installed, ran self-update, all good, ran the symfony serve command and got that error. Couldn't figure out what was going on so I downloaded again the Symfony Cli and this time it worked. Don't know why it didn't work the first time but well, at least it's working now.

    Thanks for the help.

    Cheers

  • 2019-04-26 Victor Bocharsky

    Hey Ricardo,

    Are you talking about Symfony console, i.e. bin/console? If so - you're on the wrong way, you need to use Symfony CLI client that we use in this course. It's a standalone application that you need to download from https://symfony.com/download - find a way to do this for your OS, and then follow hints from the installer. When you install it and move to the "/usr/local/bin/" - you can run the server with "symfony serve" command. And "symfony server:ca:install" command will be available as well for you.

    P.S. So the "bin/console" Symfony Console component and the new Symfony CLI client are different things :)

    Cheers!

  • 2019-04-26 Victor Bocharsky

    Hey Cavisv,

    Great, glad it helps! Unfortunately, I don't use Windows, can't help more with this error. If you still have this issue - feel free to report it to Symfony, I think they can help with it.

    Cheers!

  • 2019-04-25 Ricardo Gonçalves

    Hello,
    I'm having some issues installing the server.
    As expected I have the [InvalidArgumentException] Command "serve" is not defined. so I tried to run the installation command but I'm getting a [InvalidArgumentException] There are no commands defined in the "server:ca" namespace. . I also tried to reinstall symfony but I still get the same results.
    Did anyone have this issue?? (Mac OS btw)

  • 2019-04-25 cavisv

    After doing a Symfony update it works!
    Only there remains an error SEC_ERROR_UNKNOWN_ISSUER
    But I can click through that.
    Thanks

  • 2019-04-25 cavisv

    Thanks for the quick reply!

    Yes, I was already using http, that works fine.

    I use "symfony serve"

    symfony -v gives "Symfony CLI version v4.5.2 (c) 2017-2019 Symfony SAS"

    I already tried Chrome, that gives ERR_SSL_PROTOCOL_ERROR

  • 2019-04-25 Victor Bocharsky

    Hey Cavisv,

    Well, first of all, you can try to load the page without SSL, i.e. use HTTP instead HTTPS for the protocol. Does the http://localhost:8000 works for you?

    In this course we suggest to use "symfony serve" command instead of the old "bin/console server:run" one. Do you use "symfony serve"? What version of "symfony" CLI do you have? You can check with "symfony -v". Probably updating to the latest version may fix the problem. Also, could you try the same https://localhost:8000 URL in Google Chrome instead of Firefox? Does it work there?

    Cheers!

  • 2019-04-25 cavisv

    Hi, when I go to https://localhost:8000 it says the secure connection failed, SSL_ERROR_RX_RECORD_TOO_LONG
    I have Windows 7 and Firefox

    Any ideas?

  • 2019-03-26 Scottie Gutman

    Thank you for your, Victor. I was hoping for a secret command line argument like sudo /home/sgutman/.symfony/bin/symfony serve --port=80 --host:0.0.0.0. Unforturnately, that did not work. Maybe in the future. Again, thanks.

  • 2019-03-26 Victor Bocharsky

    Hey Scottie,

    Yes, Symfony server via bin/console supports only HTTP, you need to use "symfony serve" for HTTPS support. And you can specify a port explicitly like:
    $ symfony serve --port=80

    You can try it, but probably you would need to run this command with sudo to grant access for this, though it depends on your OS.

    P.S. to know more about any command - run the command with --help at the end, like:
    $ symfony serve --help

    What about the IP - not sure if it's possible, at least I don't see it in the help output.

    Cheers!

  • 2019-03-26 Scottie Gutman

    Thank you for the reply. But I wanted to user Symfony Serve to get https. AFAIK, the console server only does http.

  • 2019-03-25 Diego Aguiar

    Hey Scottie Gutman

    Yes, you totally can. Just run bin/console server:start 0.0.0.0:80

    Cheers!

  • 2019-03-25 Scottie Gutman

    Hello guys, I was wondering if it is possible to set the IP to 0.0.0.0? I see I can set the --port=80. It's handy so that phones/devices on my network can easily connect.

  • 2019-03-25 Scottie Gutman

    I don't have a fix, but here is a workaround. You can change a setting in chrome. chrome://flags/#allow-insecure-localhost and set to enable. I got the info here and it worked for me: https://stackoverflow.com/q...

  • 2019-03-21 Diego Aguiar

    Hey Mesut Hazen

    That's a problem between your DB version and the DB charset. You have 2 options

    1) Update to MySQL 5.6 or higher

    2) Set the field's length to 181 (or is it 191? I don't remember, but you can play with that number)

    Cheers!

  • 2019-03-21 Mesut Hazen

    Hello Ryan, i have an error during setup. i cant migrate and also tried schema update too and same error

    An exception occurred while executing 'CREATE TABLE tag (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, slug VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_389B783989D9B62 (slug), PRIMARY KEY(id
    )) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB':

    SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

  • 2019-03-15 Victor Bocharsky

    Hey Steve,

    Haha, glad you found the solution ;)

    Cheers!

  • 2019-03-15 Steve

    Never-mind. I needed to download and install the "read the instructions in full" command...

  • 2019-03-15 Steve

    HI. When running symfony serve I get

    [InvalidArgumentException]
    Command "serve" is not defined.

    Am I missing something?

    Cheers

    Steve

  • 2019-03-10 weaverryan

    Hey Dan Meigs!

    I agree! So, let's try *one* more thing. And if this turns out the same, then I think we've found a bug and will have a case that we can open an issue about. Here is the last thing:

    1) Create a totally new directory - not even a Symfony project
    2) Create a public/ directory with an index.php file inside. That file can be blank - it doesn't matter
    3) Also create a public/app.css with just a few lines of valid CSS content - doesn't matter
    4) From the root of the new directory, run the normal symfony serve. That should see your public/index.php file and start the web server completely like normal
    5) In your browser, open your debugger network tools, and go directly to https://localhost:8000/app.css. Look at the response headers - what is the Content-Type of the app.css file? Here's a screenshot example of what I'm talking about doing, using a CSS file from SymfonyCasts, where you can see the content-type is text/css https://imgur.com/a/JsCOklD

    I'm expecting you'll see application/x-css. If you DO See text/css, then go back to your Symfony project and try to surf directly to a problematic CSS file in your browser and repeat the same thing. I believe the Symfony server is sending your CSS file back to the browser with the incorrect Content-Type header. That's what we're verifying, in a super-stripped down directory.

    Let me know what you find out! Cheers!

  • 2019-03-07 Dan Meigs

    Hey weaverryan

    I tried symfony server --no-tls and got the same result. I also tried to call the compiled css file directly as <link rel="stylesheet" type="text/css" href="/build/app.css"/> with the same result. Then I replaced app.css with a very simple css file, just in case. Again, same result.

    This perplexing!

  • 2019-03-07 weaverryan

    Hey Dan Meigs !

    Awesome digging :). I think this is a problem with the new Symfony server -that's my instinct. There are a few reasons. When you use Encore in the "normal" mode (not dev-server), it writes physically files. So... if there is *any* issue downloading then, that's really the fault of your "web server". I further think this because you said that bin/console server:run *does* serve them correctly - the problem is only with the symfony serve command. When you use the `dev-server` command in Encore, your files are served by a totally separate Node server - so it *does* make sense that they would work in that context, but not in the normal "build" context.

    Let's experiment: try running the server like this:


    symfony serve --no-tls

    That will start the web server simply in http instead of https. I don't have any specific reason why I think that might make a difference - but let's try it. Beyond that, I think we should explore having you open an issue about this. Oh, one other thing to try is simply creating a `public/build/foo.css` file manually and putting some CSS in it. If you manually add a link tag in your template to this, does it download? Or do you get the same error.

    Cheers!

  • 2019-03-07 Dan Meigs

    Victor,

    The doctype is just as you showed. I added the explicit type definition, and that did not change anything.

    I use Chrome normally, but I tested in Edge and got the same result.

    When I run encore dev-server, the stylesheet link resolves as:

    <link rel="stylesheet" type="text/css" href="http://localhost:8080/build/app.css"/>

    The stylesheet loads and everything works perfectly.

    When I run encore production, the stylesheet link resolves as:

    <link rel="stylesheet" type="text/css" href="/build/app.73e7f49c.css"/>

    and the stylesheet won't load and throws the warning I showed earlier.

    To leave no stone unturned, I changed my template so it would render as

    href="localhost:8080/build...

    but that did not make a difference.

    I hope you can see a problem that I can't. Thanks!

  • 2019-03-07 Victor Bocharsky

    Hey Dan,

    Hm, what browser do you use? Could you try in a different browser? Or in incognito mode for example? And what HTML doctype do you have in your base layout, is it:


    <!doctype html>
    <html>...</html>

    Try to explicitly specify type of the loaded file as:


    <link rel="stylesheet" type="text/css" href="{{ asset('build/app.css') }}">

    Does it help?

    Cheers!

  • 2019-03-07 Dan Meigs

    Hey Ryan,

    My template has:


    {% block stylesheets %}
    <link rel="stylesheet" href="{{ asset('build/app.css') }}"/>
    {% endblock %}

    When I view source, I see

    <link rel="stylesheet" href="/build/app.73e7f49c.css"/>

    When I click on the link, the stylesheet is downloaded as an attachment, and I see the following in my console:

    Resource interpreted as Stylesheet but transferred with MIME type application/x-css: "https://localhost:8000/build/app.73e7f49c.css".

    I don't get it!

    Dan

  • 2019-03-04 weaverryan

    Yo Dan Meigs!

    Hmm... interesting! Well, let's do some digging :). Ultimately, your Webpack Encore assets are just normal, boring, physical files inside your public/ directory after they're built - so nothing "weird" should be happening. I'd try this:

    1) Restart the new symfony server and browser to your app
    2) View source (or inspect element), copy one of the paths to your assets - css or JS - and surf to it - so it'll be something like https://localhost/build/app.css. Do you see the contents or some error?

    The first difference that comes to mind with the two setups is that the symfony server gives you https, instead of http. I can't think why that would effect things - but it possibly may. Also, do you see any errors in your browser's console?

    Cheers!

  • 2019-03-03 Dan Meigs

    Hey Guys,

    I downloaded and installed the symfony cli on my Windows machine. When I try to use the new symfony server to browse my application, which is built with webpack encore, my stylesheet (and presumably my .js assets) is not loaded. (It still works with php bin/console server:run.)

    Is there a configuration step I'm missing to use the symfony server with webpack encore assets?

    Thanks!

  • 2019-02-28 Victor Bocharsky

    Hey Napester,

    Yes, you're right, you can continue with this tutorial after Symfony4 Forms one. Actually, File Uploads course code is based on Symfony 4 Forms code but with tiny upgrades, so if you want match the video 100% - download course code and start from "start/" directory. But you want, you can continue your project after Symfony 4 Forms, just keep in mind that code might slightly be different due to upgrades.

    Cheers!

  • 2019-02-28 Napester Shine

    Hi,

    Thanks for another great one. I am just confused with the flow of tracks. I finished all the videos mentioned in SF4 series and coded myself together. so is this next one in the line after SF4 Forms track. or I need to do other one before it ?

    Thnaks

  • 2019-02-26 Diego Aguiar

    Hey Asko Ohmann

    Being honest, I have not done that before but I found good info about what you can do: https://github.com/aspnet/D...

    Give it a try and let us know. Cheers!

  • 2019-02-25 Asko Ohmann

    Hi,

    Any idea on how to make the cert work on Windows with WSL?

    Running "symfony server:ca:install" in WSL will install the certificate on the subsystem but accessing the server from windows browser will deem the website unsafe as the certificate is presumably assigned to the subsystem virtual machine.