Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Uploading a File with PHP and HTML5

Elliott Frazier sent me an email a few weeks ago asking about a short demo on how to upload files to your server using PHP. I think this would be helpful to a lot of folks and a good starting point.

Thanks again for your suggestion!

20 Answers

Here is a quick example for you Elliott Frazier

You can find all the demo files here

Here are several links that will help you tremendously over time and are a great reference for common pitfalls or other methods you may not have know about.

php.ini configuration for file uploads

Post method upload documentation

PHP 5.3 Fileinfo documentation

Fileinfo predefined constants

move_uploaded_file function documentation

PHP file upload error message definitons

Have fun folks!

Hi Hampton, thanks for this demo. The one bug I have encountered is in the situation of a user not uploading anything and pressing the upload button. This will produce errors.

If a file is not uploaded, the $_FILES array is still generated, albeit with the values of the array being empty. However this does mean that:

echo count($_FILES);
// This will return 1 even if no file has been uploaded and the user presses upload.

So I think a better way to do this to ensure there are actually values inside the array would be

if( !empty( $_FILES['name'] ) ) {
// run code here
}

This way we only run our PHP code if the $_FILES array is not empty and has values, i.e. a file has actually been uploaded.

I would like to be able to download this video. We have the option to download all videos in the Tracks so could we please have a way to download this one too?

Hi Wendell - Let me ask the team when they are back in on Monday and get back to you. Good question.

Look at with devtools at the code and take it over another window and then save it. The filextension is .webm and this could be played with VLC player

devtools window

However i'll let below the link to the webm video so you could download it.

https://wpc.a8b5.edgecastcdn.net/80A8B5/treehouse/videos/TH-OnTrack-FileUpload-534.webm?514809d2869d73b56fd93d125510035500c5c9da011d1715abd519cea4a3a1da11f0

oh yea!! I should have thought of that! I've done stuff like that before. Thanks :D

You can change the extension to .mp4

Francisco Payá -

Changing extensions won't magically change the encoding of the video, it will still have a webm encoding not a mp4 encoding, regardless of what you change the extension to.

Sorry, I can't edit my last comment.

If you use Chrome you'll get the .webm but if you use Safari you'll see the .mp4 file. I've recorded a screencast.

http://quick.as/rjcbwg

Wow, this could absolutely not have come at a better time for me. I'm building a PHP site for the first time for my job, and quite literally the very next thing I need to do is incorporate the ability to upload files! Thank you, and thanks to the guy that asked for this!

I have been waiting to find out how to do this! thanks so much!

The link appears to be broken. Thanks a lot for the demo, much appreciated.

Thanks for the heads up Slavi Todorov. All fixed now.

You're welcome.

Thanks a bunch! Cant wait to dive into it!

Very neat! But I'm not able to download the demo files, have they been uploaded? Thks

it is working now, thks

Excellent example.

Thank you very much.

wow, nice... I will wait the next video about upload file (images) with progress bar. thx

I plan to fake one using JS once the upload button is triggered. lol

Hallo, i am trying to validate different types, and it's not working. why is that?

// validate file
    if ($file_mime !== 'image/jpeg' OR $file_mime !== 'image/png' OR $file_mime !== 'application/zip' OR $file_mime !== 'image/gif') {
    die('we only want jpg,png,gif and zip files, and you sent us this: ' . $file_mime);
    }

thanks

Because of how you structured your logic, it will always return "true" to the if statement if the file is any of those types. This is because any logical true in a string of OR statements will return true to the if statement. Then the die() function will be called.

A better structure might be: if ( ! ($file_mime === 'image/jpeg' OR $file_mime === 'image/png' OR $file_mime === '.... ) ) { die() }

love it, thanks

Needed to know this! thank you. :)

Great timing, I was just wondering how to do this! Thanks for the video!

Many thanks for this clear explanation!

Good stuff great video!!!

Just a a note !!!

I was having trouble accomplishing this task, just to realize that the php version that i am using is PHP Version 5.2.4-2ubuntu5.27 does not support finfo_open() error log shows : PHP Fatal error: Call to undefined function finfo_open()to then only to find out that php 5.3.0 and above supports it. Does anyone knows the way around this using php 5.2.4?

Good Morning Juliano Vargas - Is there any reason you have to stay on version 5.2.4? That version was released on 30-Aug-2007. I would say it is time to think about an upgrade.

This type of file checking was added in 5.3 but I have seen mention of magic_open as a work around before 5.3.

Hope this helps you.

I got this message: Fatal error: Call to undefined function finfo_open()

why it saying it's undefined? i'm running php 5.4.16

also I took that out and got the mime type like this but got "move_uploaded_file(entry_pics/pets/baby leopard.jpg): failed to open stream: No such file or directory in":

   $tmp_name = $_FILES['entry_pic']['tmp_name'];
    $file_mime = $_FILES['entry_pic']['type'];

    if($file_mime !== 'image/jpeg'){
      die("We only want jpeg files");
    }

    if(!move_uploaded_file($tmp_name, 'entry_pics/pets/'.$_FILES['entry_pic']['name'])){
      echo "File not uploaded";
    }

hello Wendell - if you are using windows: Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension. If this is not the case, please paste all of your code and give a bit more info about your development setup so I may try to reproduce it.

thanks for the tip on the php_fileinfo.dll... fixed that and I no longer get the undefined function error when i use the exact code used in the video for that part... I also updated my version of php and xampp but i'm still getting the move_uploaded_file error

here's my entire code:

  include('../inc/db.php');
  $entry_text=$_POST['entry_text'];
  if(count($_FILES)){
    $tmp_name = $_FILES['entry_pic']['tmp_name'];

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $file_mime = finfo_file($finfo, $tmp_name);
    finfo_close($finfo);

    if($file_mime !== 'image/jpeg'){
      die("We only want jpeg files");
    }

    if(!move_uploaded_file($tmp_name, 'entry_pics/pets/'.$_FILES['entry_pic']['name'])){
      echo "File not uploaded";
    } else {
      $db->query("INSERT INTO crafts SET entry_pic_path = 'entry_pics/pets/".$_FILES['entry_pic']['name']."',
        entry_text = '".$entry_text."', date = CURDATE()");
      header("location: ../pets.php");
    }
  }

Perhaps a folder permissions issue? Most likely it has to do with the second argument of move uploaded file. Try moving all that to a variable and then var_dump to see if you get what you expect. Maybe it has no extension on the name. Also, take a look at the php function getcwd to help assemble your expected path.

yea it was the second argument.. my file path was messed up... I just had to add "../" to the start of the file path on the move_uploaded_file function and it worked just fine :D thanks again for the video and the feedback :D