Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Uploading files

From: Validating and Processing Forms with JavaScript and PHP

Video: Uploading files

Let's go ahead and add file uploading capabilities to our form. Before we do that, we're going to to need to create an uploads folder on our server. So, here I am on my FTP application, I'm going to right-click to select new folder. This is usually the way that you create a new folder in most FTP apllications. You can usually also go to the File menu. I'll call this uploads. Now we need to set the permissions of the folder so that PHP can write to it. Once again I'm going to right-click and select this time Get Info. That permissions right now are seven five five, which means that only users can write to this folder. I'm going to change it to seven seven, seven, which means that anyone including our application is going to be able to write tot his folder. So now I hit Apply, and I'm done with the FTP program. Now I need to go to the page and add an input field to take our files. This is going to be another list item and input field's going to by type of file. My name is going to be my profile pics.

Uploading files

Let's go ahead and add file uploading capabilities to our form. Before we do that, we're going to to need to create an uploads folder on our server. So, here I am on my FTP application, I'm going to right-click to select new folder. This is usually the way that you create a new folder in most FTP apllications. You can usually also go to the File menu. I'll call this uploads. Now we need to set the permissions of the folder so that PHP can write to it. Once again I'm going to right-click and select this time Get Info. That permissions right now are seven five five, which means that only users can write to this folder. I'm going to change it to seven seven, seven, which means that anyone including our application is going to be able to write tot his folder. So now I hit Apply, and I'm done with the FTP program. Now I need to go to the page and add an input field to take our files. This is going to be another list item and input field's going to by type of file. My name is going to be my profile pics.

I'll set the ID to the same thing. And I'm going to use the accept the attribute here to prevent some browsers that are supported from taking anything other than a JPEG file. This field uses a MIME type, so I'll put image/jpeg. You can also put image/star if you want to take any type of image file. I'm going to add a couple more things. I'll need a label for this, so add a label. Label is going to be for my profile pics, and the label is going to say, profile picture.

I'll put in an instruction to make sure people know that these files have to be jpeg, and I'll ask for files that are smaller than 100k. I'm going to also add a hidden input field, this hidden input field will have a special name that PHP can recognize, called max files size. Now 100k turns out to be 102400. So, the value of this field should be the size that you want in bytes. Since 1kB is 1024 bytes, 100 kilobytes would be 1024 plus two zeros. Okay, I'm going to save this and now I'm ready to go back into my script. So, the first thing that I want to do in my script, is make sure that we have no errors before we go into this new file uploading section. I'm going to look for the email section which is right down here. And right before the form data array, I'll insert an IF statement. And in that IF statement, I'm going to check to make sure that form errors, which normally has a value of whether or not our form has errors, is true or false.

If it's not false, then I'm going to perform my file upload. Now I'll create some special variables that I'm going to need to set up my uploading functions. First I'll get the temporary name from the file superglobal. Notice that the first part of the files array has the name used in our form input field. Now you don't need to necessarily do this, you can also find out what the original name of the file was. We'll create a variable for that, called Upload file name. ANd it's going to be equal to the same thing as up here, except instead of temp name, this is going to be name.

Here's why this is a little bit dangerous. If you don't use unique names, and somebody uploads another file with the same name as your file later on, the previous file's going to be overwritten. So I'm going to create a date so I can use it as part of my file name. That way the name of every file will be unique. This is just a standard PHP date string. We'll need to create a new file name. We'll use our date in combination with our upload file name. We'll put in the name of our folder, plus the safe date variable which has the date that the file was uploaded, then we'll use an underscore, and then we'll use the upload file name. If we want to create a normal URL link to this file, we'll have to get it from a few superglobals.

We'll call this variable upload url. So, just like a regular URL, it'll start with http://, and then I'm going to use the _SERVER superglobal. And I'm going to ask for the server name, which normally has the domain of the Web site. Then I'll use the _SERVER superglobal again, this time I want to get the request URI. The request URI gives you the URL of the current page from the root of the server. But we need to get rid of the last part, because that's the name of this file, process.php.

I'll use the DIR name function, and I'll pass along our request URI. Then we'll add a slash and then add our new file name. So now that we're ready setting up variables, we're ready for our IF statement. What we need to do is take the file from temporary location that PHP puts it in into the folder that we created with the FTP application. To do that, we'll use the Move Uploaded Files function. So we'll create an IF statement and say move uploaded file, and it wants two things: the file name and destination. File name is going to be the temporary file name tmp name, and the destination is going to be our new file name.

Now if this comes back as true, then we'll add a variable called message msg and give a message of file uploaded. If it's not true, then we're going to create another message with an error and we'll pass it along to file error variable from the file superglobal. We'll also set the form errors variable to true. And we'll end the IF statement. Let me comment this other one as well. If you want to, you can add a value to your form data associative array with the URL of the image.

So now I'm going to save this file and go back into my form, make sure that I refresh. You can see the input field is right there. So I'm going to put in a name here and a password, or it's going to complain. And then I'll hit the Choose File button and select this cute image of a doggie that I have. And I'm going to hit the Send button. So it looks like I have a spelling mistake as well as a file error. Now, I know what this is, and this is a very common mistake to make when doing these forms. If I go back to my index.php file, I notice that my method is set to post, but my enctype is not correct.

My enctype should be set to multipart form data. So, what that does is, since this form has a file in it, it can't just send the file as it normally would through the post method. It has to be specially encoded, so that it can be transmitted over the web. So, this enctype attribute tells it to format the file properly, and we need to make sure that we have that. Really, it happens to me quite a bit. It's sort of an easy thing to forget. When you're doing an image, a lot of times you tend to focus on the fields right here.

I'm going to save this and go back into my process.php file, and find that spelling mistake, could dadadadadadada end. So let me delete that d, save it. Let's go back to our form, and I'm going to reload it. And I'll try this again. I'm going to choose File, find my doggie photo and just put in some password here. And now I'm going to hit the Send button, and it says, thanks for filling out our form. Now let's go into our FDP program. I'm going to open up the uploads folder, and I'm going to hit Do a Refresh because a lot of times it won't show the upload right away. And there's my doggy file.

Notice that it has, in addition to its original name, the date and time that the file was saved. If I hit the spacebar, I can take a look and see that it's the same folder that I uploaded. There's one more thing that we can do to clear this up. Notice that the form kind of still shows up after you upload the file. That's not the cleanest thing in the world, so I'm going to go into my index.php document. What I will do is modify this statement right here so that if the message is sent, then it's going to print it out.

Otherwise it's going to print out the form, and then I'll need another PHP statement at the bottom of the form that just ends the IF statement. So I'm going to save this go back into our form. I'll go ahead and reload it and then I'm going to fill it out again. I'll choose the same file and I'm going to hit Send. I really don't want to save the password here, but notice that the form is now gone, which is what you want. You don't really want the form to still be there. I want to just thank people for filling out the form. Now let's go back into our FTP program, I'm already in the uploads folder, if I refresh my page, I should see two copies.

And this is really important and why you want don't want to just output the original name of the file. You want to make sure you add something like a date and time, so that if somebody uploads more than one photo at the same time, they're going to have different names. Uploading documents doesn't have to be the hardest thing in the world. All you have to do is make sure that you understand the file's super global. Once you understand the file's superglobal, you can create variables that assign file names and put your files where they need to be.

Show transcript

This video is part of

Image for Validating and Processing Forms with JavaScript and PHP
 
Expand all | Collapse all
  1. 3m 36s
    1. Welcome
      1m 9s
    2. What you should know
      1m 2s
    3. Using the exercise files
      1m 25s
  2. 12m 50s
    1. Understanding forms
      2m 2s
    2. Working with form fields
      7m 4s
    3. Using the form tag
      3m 44s
  3. 19m 23s
    1. Using input validation
      2m 10s
    2. Adding required fields and placeholders
      1m 31s
    3. Constraining numeric and date fields
      2m 32s
    4. Accepting multiple entries
      1m 41s
    5. Limiting uploads by MIME types
      2m 35s
    6. Assisting text input with a datalist
      1m 55s
    7. Constraining with regular expression patterns
      6m 59s
  4. 42m 13s
    1. Accessing forms
      3m 57s
    2. Looking up form elements
      3m 35s
    3. Handling focus changes
      2m 47s
    4. Detecting the onchange event
      4m 31s
    5. Using the selectedIndex property
      2m 30s
    6. Dynamic validation with regular expressions
      7m 0s
    7. Creating a generic input validation function
      4m 31s
    8. Validating in older browsers with Modernizr
      7m 32s
    9. Interrupting form submission with onsubmit
      5m 50s
  5. 15m 20s
    1. Understanding jQuery
      3m 47s
    2. Validating on submit with jQuery
      3m 45s
    3. Building interactive jQuery validation
      2m 34s
    4. Using the jQuery Validation plugin
      5m 14s
  6. 32m 57s
    1. Communicating with PHP servers
      2m 27s
    2. Retrieving data from superglobals
      8m 18s
    3. Using server-side validation
      4m 59s
    4. Adding in-page validation
      5m 22s
    5. Mirroring input data back to the user
      7m 46s
    6. Sanitizing form input
      4m 5s
  7. 43m 29s
    1. Mailing form data
      8m 28s
    2. Understanding file uploads
      3m 1s
    3. Uploading files
      9m 20s
    4. Processing form data with AJAX
      8m 14s
    5. Preparing your database
      5m 50s
    6. Pushing data
      8m 36s
  8. 1m 17s
    1. Next steps
      1m 17s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Validating and Processing Forms with JavaScript and PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.