Uploading files in PHP

The Code

upload.htm

<html>

<form action="myupload.php" method=post enctype="multipart/form-data">
submit this file: <input type=file name="userfile"><br>
<input type=submit><br>
</form>
</html>

myupload.php

<html>
<?
// In PHP earlier then 4.1.0, $HTTP_POST_FILES should be used instead of $_FILES.
if(!empty($_FILES["userfile"])) {
    $uploaddir = "/upload/" // set this to wherever
    //copy the file to some permanent location
    if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploaddir . $_FILES["userfile"]["name"])) {
        echo("file uploaded");
    } else {
        echo ("error!");
    }
}
?>
</html>

myupload.php handles the uploaded file. In PHP, posted files can be accessed via the $_FILES array. This array in turn has an array with the following entries:

  • $_FILES["userfile"]["name"]
    The original name of the file on the client machine.
  • $_FILES['userfile']['type']
    The mime type of the file, if the browser provided this information. An example would be "image/gif".
  • $_FILES['userfile']['size']
    The size, in bytes, of the uploaded file.
  • $_FILES['userfile']['tmp_name']
    The temporary filename of the file in which the uploaded file was stored on the server.

When a posted file is retrieved, PHP automatically saves the file in a temporary directory. We copy the file to a permanent location using the move_uploaded_file() function, which simply takes the temporary file name (accessed by 'tmp_name') and the location to move it to.

You might also like...

Comments

About the author

S.S. Ahmed United States

S.S. Ahmed is a senior IT Professional and works for a web and software development firm. Ahmed is a Microsoft Office SharePoint Server MVP. Ahmed specializes in creating database driven dynamic...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth