Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL

Home > PHP > Uploading Filesprinter version

PHP Uploading Files

PHP allows files to be uploaded to the server by users via the web browser using an HTML form (form input is covered in the HTML Forms Input and Textarea tutorial).

Note: Allowing users to upload files to your server presents a security risk. Never allow executable files to be uploaded and make sure you understand all the potential risks and how to guard against them.


The HTML form element requires three attributes.



The attribute type of the input element is set to file and the name attribute is set to a name that will be used by the file handling script to identify the uploaded file.

The input element displays a text box and browse button to allow the user to either enter the path to the file or to browse for the file on their machine.

The HTML File Upload Form
<form enctype="multipart/form-data" action="file_handling_script.php" method="post">
    <input type="file" name="user_file">
    <input type="submit">
</form>


Finding Information on The Uploaded File

When the file is uploaded it's placed in a temporary directory by the server and is deleted when the script ends, unless something is done to handle it.

Information about the uploaded file can be found in the global variable $_FILE in an associative array.

Note: If your version of PHP is earlier than 4.1.0 then use $_HTTP_POST_FILES.


The first element in the associative array holds the name that was used in the HTML form - in this case 'userfile'.



Once a file has been uploaded you have choices about what you will do with it. You may want to perform file operations on it or move it to somewhere on the server as is.

Security Considerations

Whatever you decide to do with the file, before you do it, you must test for a malicious upload that could wreak havoc on your server.

Using is_uploaded_file()

If you intend to perform file operations on the file rather than move it to somewhere on the server as is then you should use this function, which will return TRUE if the file was actually uploaded to the server using the post request.

Example of is_uploaded_file()
<?php
    if (is_uploaded_file ($_FILE(['userfile']['tmp_name']))
    {
        // The file is OK so perform file operations
    }else{
        echo ('There was an error');
        exit;
    }
?>


Using move_uploaded_file()

This function also returns TRUE if the file was actually uploaded to the server using the post request so if used, is_uploaded_file is not required.

As well as the first two arguments, which are the same as is_uploaded_file(), a third argument is required. This holds the file name and path on the server where the file is to be placed.

However, before a file is moved a check should be made on the size and type of the file. A huge file could overwhelm your server and an executable file could be uploaded and run from the user's browser to create mischief.

For example if the user is required to upload a .jpg file then only allow this type or if various types are allowed then check for each with a switch statement.

Example of move_uploaded_file()
<?php
    // Check the file size
    if ($_FILE['userfile']['size'] > 655367)
    {
        echo ('File size too large!');
        exit;
    {

    // Check the file type
    if ($_FILE['userfile']['type'] != 'image/pjpeg')
    {
        echo ('Invalid file type!');
        exit;
    {

    if (move_uploaded_file ($_FILE(['userfile']['tmp_name'], 'images/photo.jpg'))
    {
        echo {'Your file has been uploaded.');
    }else{
        echo ('There was an error with your file!');
    }
?>


Previous - PHP include and require Previous - Include and Require    Next - File Functions Next - PHP file functions


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsSorting ArraysUser-Defined FunctionsInclude and RequirePHP uploading filesUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook
Tips and TricksPage TemplatesForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.