PHP File Upload

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

PHP provides the facility to upload files to a server.

Create an Upload-File Form

To allow a user to upload files from a form can be very useful. For eg there are various sites where we can upload images and keep theem there, or sites where we can upload our resumes.

Look at the following HTML form for uploading files:

    <html>
    <body>
    <form action=”upload_file.php” method=”post”
    enctype=”multipart/form-data”>
    <label for=”file”>Filename:</label>
    <input type=”file” name=”file” id=”file” />
    <br />
    <input type=”submit” name=”submit” value=”Submit” />
    </form>
    </body>
    </html>

Notice the following about the HTML form above:

  • The enctype attribute of the <form> tag specifies which content-type to use while submitting the form. The value “multipart/form-data” is used when a form requires binary data to be uploaded, like the contents of a file.
  • The type=”file” attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field

Create the Upload Script

The “upload_file.php” file contains the code for uploading a file:

    <?php
    if ($_FILES["file"]["error"] > 0)
    {
    echo “Error: ” . $_FILES["file"]["error"] . “<br />”;
    }
    else
    {
    echo “Upload: ” . $_FILES["file"]["name"] . “<br />”;
    echo “Type: ” . $_FILES["file"]["type"] . “<br />”;
    echo “Size: ” . ($_FILES["file"]["size"] / 1024) . ” Kb<br />”;
    echo “Stored in: ” . $_FILES["file"]["tmp_name"];
    }
    ?>

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

  • $_FILES["file"]["name"] – the name of the uploaded file
  • $_FILES["file"]["type"] – the type of the uploaded file
  • $_FILES["file"]["size"] – the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] – the error code resulting from the file upload

This is a very basic way of uploading files, which is very less secure. For security reasons, you should add restrictions on what the user is allowed to upload.

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.