Upload Files Part I: PHP uploader

User Rating:  / 2
View Comments

You are just missing one key feature in your site and you know it. That key feature is to be able to upload files in it. ...hmmm, why??

So, yes, you need a File Uploader!!

Let's differentiate 3 clear steps in the process:

  1. Create a section in your page for the file upload, aka a form.
  2. Routine to process the upload, name it and place somewhere in the file system
  3. Communicate your customer the results of the File Upload (In our example we will have steps 2 and 3 in same one)

let's go for it!!.

Create the Form

First of all let's create a simple html form to be able to upload files.


// make a note of the location of the upload handler script 
$uploadHandler = './fileUpload.php'; 

// set a max file size for the html upload form 
$max_file_size = 1500000; // size in bytes 

// now echo the html page 
<form id="Upload" name="Upload" action="upload.php" enctype="multipart/form-data" method="post">
<h1>Upload example Form</h1>
<p><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>"></p>  
    <label for="file">File to upload:</label> 
     <input id="myImage" type="file" name="myImage"> 
    <label for="submit">Press to...</label>
    <input id="submit" type="submit" name="submit" value="Upload me!">

The Upload Process

First let's define the path where the files are going to be stored

// The base path in the server of the Document Root. For example for a XAMPP installations should be something as
// but if you don't exactly know it just use: $basePath='$_SERVER['DOCUMENT_ROOT'];
// This is the path within the document root of your web server where you want the files to be stored. This will be the path visible from the user:
$extPath= 'http://yourSite/userfiles/';


Now let's deal with the upload

// Filename will be the one in the input of type "file".
$fileName = 'myImage'; if ($_FILES[$fileName]['error'] == 0) {
// The file you are looking for is this one: $_FILES[$fileName]['tmp_name']) but it is in a temporary folder and with a name such as ../temp/phpZe2S. Let's move the file to a path accesible via http and with a correct name: $_FILES[$fileName]['name'].
if (!copy($_FILES[$fileName]['tmp_name'], $intPath.$_FILES[$fileName]['name']))
echo "failed to copy $file...\n";
echo "Your Uploaded file is: ".$extPath.$_FILES[$fileName]['name'];
echo("There was an error Uploading the File: ".$errors[$_FILES[$fieldname]['error']], true);

As easy as this!!!.

What to Expect in Upload Files Part II?