Return to site

File Upload

broken image


WeTransfer is the simplest way to send your files around the world. Share large files up to 2GB for free. Send file as binary content (upload without form or FormData) In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

  • PHP Tutorial
  • Advanced PHP
  • PHP Form Examples
  • PHP login Examples
  • PHP AJAX Examples
  • PHP XML Example
  • PHP Frame Works
  • PHP Design Patterns

Upload Documents

  • PHP Function Reference
  • PHP Useful Resources
Download
  • Selected Reading

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.

Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps −

  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.

  • The user clicks the browse button and selects a file to upload from the local PC.

  • The full path to the selected file appears in the text filed then the user clicks the submit button.

  • The selected file is sent to the temporary directory on the server.

  • The PHP script that was specified as the form handler in the form's action attribute checks that the file has arrived and then copies the file into an intended directory.

  • The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.

An uploaded file could be a text file or image file or any document.

Creating an upload form

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

It will produce the following result −

Creating an upload script

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables −

  • $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.

  • $_FILES['file']['name'] − the actual name of the uploaded file.

  • $_FILES['file']['size'] − the size in bytes of the uploaded file.

  • $_FILES['file']['type'] − the MIME type of the uploaded file.

  • $_FILES['file']['error'] − the error code associated with this file upload.

Example

Below example should allow upload images and gives back result as uploaded file information.

It will produce the following result −

Ah yes, the good old problem of file uploads. The basic idea of fileuploads is actually quite simple. It basically works like this:

  1. A

    tag is marked with enctype=multipart/form-dataand an type=file> is placed in that form.

  2. The application accesses the file from the filesdictionary on the request object.

  3. use the save() method of the file to savethe file permanently somewhere on the filesystem.

A Gentle Introduction¶

Let's start with a very basic application that uploads a file to aspecific upload folder and displays a file to the user. Let's look at thebootstrapping code for our application:

So first we need a couple of imports. Most should be straightforward, thewerkzeug.secure_filename() is explained a little bit later. TheUPLOAD_FOLDER is where we will store the uploaded files and theALLOWED_EXTENSIONS is the set of allowed file extensions.

Why do we limit the extensions that are allowed? You probably don't wantyour users to be able to upload everything there if the server is directlysending out the data to the client. That way you can make sure that usersare not able to upload HTML files that would cause XSS problems (seeCross-Site Scripting (XSS)). Also make sure to disallow .php files if the serverexecutes them, but who has PHP installed on their server, right? :)

Next the functions that check if an extension is valid and that uploadsthe file and redirects the user to the URL for the uploaded file:

So what does that secure_filename() function actually do?Now the problem is that there is that principle called 'never trust userinput'. This is also true for the filename of an uploaded file. Allsubmitted form data can be forged, and filenames can be dangerous. Forthe moment just remember: always use that function to secure a filenamebefore storing it directly on the filesystem.

Information for the Pros

So you're interested in what that secure_filename()function does and what the problem is if you're not using it? So justimagine someone would send the following information as filename toyour application:

Assuming the number of ./ is correct and you would join this withthe UPLOAD_FOLDER the user might have the ability to modify a file onthe server's filesystem he or she should not modify. This does require someknowledge about how the application looks like, but trust me, hackersare patient :)

App tamer 2 4. Now let's look how that function works:

Now one last thing is missing: the serving of the uploaded files. In theupload_file() we redirect the user tourl_for('uploaded_file',filename=filename), that is, /uploads/filename.So we write the uploaded_file() function to return the file of that name. Asof Flask 0.5 we can use a function that does that for us:

Alternatively you can register uploaded_file as build_only rule anduse the SharedDataMiddleware. This also works witholder versions of Flask:

If you now run the application everything should work as expected.

File Upload Service

Improving Uploads¶

Changelog

So how exactly does Flask handle uploads? Well it will store them in thewebserver's memory if the files are reasonable small otherwise in atemporary location (as returned by tempfile.gettempdir()). But howdo you specify the maximum file size after which an upload is aborted? Bydefault Flask will happily accept file uploads to an unlimited amount ofmemory, but you can limit that by setting the MAX_CONTENT_LENGTHconfig key:

The code above will limit the maximum allowed payload to 16 megabytes.If a larger file is transmitted, Flask will raise aRequestEntityTooLarge exception.

File Upload.dhs.tn.gov

Connection Reset Issue

When using the local development server, you may get a connectionreset error instead of a 413 response. You will get the correctstatus response when running the app with a production WSGI server.

This feature was added in Flask 0.6 but can be achieved in older versionsas well by subclassing the request object. For more information on thatconsult the Werkzeug documentation on file handling.

Upload Progress Bars¶

A while ago many developers had the idea to read the incoming file insmall chunks and store the upload progress in the database to be able topoll the progress with JavaScript from the client. Long story short: theclient asks the server every 5 seconds how much it has transmittedalready. Do you realize the irony? The client is asking for something itshould already know.

Free File Upload Direct Link

An Easier Solution¶

File Upload Form

Now there are better solutions that work faster and are more reliable. Thereare JavaScript libraries like jQuery that have form plugins to ease theconstruction of progress bar.

Because the common pattern for file uploads exists almost unchanged in allapplications dealing with uploads, there is also a Flask extension calledFlask-Uploads that implements a full fledged upload mechanism with white andblacklisting of extensions and more.





broken image