SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast doddsey_65's Avatar
    Join Date
    Sep 2010
    Location
    North East UK
    Posts
    77
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [tutorial] Uploading Files

    Whether you are wanting users to upload images or whether you want them to upload files. This tutorial will guide you through the process.

    First off we need to make a form where the user can select a file and then submit it to our server.
    To do this we will need a new page. So create the page uploadForm.html in your websites document root.

    We start our form with the <form> tag and use the respective closing tag </form>.
    The form tag comes with many options but I will only go through the ones we need for now.

    This is how our form tag will look:

    Code:
    <form name="uploadForm" action="processForm.php" method="post" enctype="multipart/form-data">
    Firstly the form name is basically our name for the form. It can be anything you want. Here we have gone for uploadForm. It's
    best that you name it something to do with the form as this will make things clearer for you.

    Action refers to where the data of the form is going to be sent to. In this example we are sending the data to processForm.php.(more later)

    Method is how the form will send the data. We have gone with the method post which means the form data is sent with the body of the form to the processing page.

    next what we need to do is to create a field where the user can select a file. we do this with the <input> tag.

    Code:
    <input type="file" name="uploadedFile" />
    The input type defines this as a file. That means that there will be a browse button next to the field which the user can click to browse through their computer files and select one to upload.

    the name again can be anything you want. It is what we will use in the process page to grab the data.

    You can also add a hidden field so you can specify the max size of a field.

    Code:
    <input type="hidden" value="999999999" name="maxSize" />
    the hidden type means that this will not appear on the form as a field.
    the value is the actual size we wish to limit to (in bytes).

    Now all we need is a submit button. This again is done with the <input> tag:

    Code:
    <input type="submit" value="Upload" />
    the type this time is submit, which basically creates a button the user can click on to submit the form. The value
    is the actual words used on that button.

    So there is our small form done. Now onto the fun stuff. The Processing.

    Remember when we created our form we supplied the action attribute as processForm.php?
    Well now i want you to create a new file in the same place as the last and call it processForm.php. make sure to save it as a php file and not html.

    This is where we get the data from the form and then use it in the way we want. In this tutorial we are going to add the file to a folder on the site root and then display it for the user.

    So i need you to also create a folder called uploads on in the same place. And this will be where the files go.

    Now processForm.php will do all of the important stuff with our file. Namely it will store it for us, show up any errors if there are any and it will display it for us.

    so to start with add the php tags into your file. This tells the browser that this script is written in php.

    Code:
    <?php
    
    
    ?>
    There are other methods of declaring php code but i wont go into them in this tutorial.

    To access data about the uplaoded file we use the super glabal array $_FILES
    Rather than go through it bit by bit you can copy all of the code below and follow the comments.

    Code:
    <?php
    
    if ($_FILES['uploadedFile']['error'] == UPLOAD_ERR_OK) // If there are no errors in the upload process
    {
          $destination = 'uploads/' . basename($_FILES['uploadedFile']['name']); // set the destination for where the file is to be transfered
          $moveIt = move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $destination);
    	  
    	  if ($moveIt === FALSE) // If the file couldnt be moved
    	  {
    		echo "Unable to move file"; // say so 
    	  }
    	  else // if it was moved
    	  {
    		echo "The file has been moved!"; // say so
    	  }
    }
    else // if there were errors in the upload process
    {
    	// show the errors
    	switch ($_FILES['uploadedFile']['error'])
    	{
    		case UPLOAD_ERR_INI_SIZE:
    		case UPLOAD_ERR_FORM_SIZE:
    			echo "Error: Invalid Size";
    			break;
    		
    		case UPLOAD_ERR_PARTIAL:
    			echo "Error: File only partially uploaded";
    			break;
    		
    		case UPLOAD_ERR_NO_FILE:
    			echo "Error: Please choose a file";
    			break;
    		
    		case UPLAOD_ERR_NO_TMP_DIR:
    			echo "Error: No upload directory";
    			break;
    		
    		default:
    			echo "Unknown Error";
    			break;
    	}
    }
    
    ?>
    You will see the errors that i have used for example UPLOAD_ERR_INI_SIZE.
    These are error codes associated with the uploaded file.

    • UPLOAD_ERR_OK: if this equals 0 then the file was uploaded successfully
    • UPLOAD_ERR_INI_SIZE: this specifies that the file was larger than the size defined in your php.ini file.
    • UPLOAD_ERR_FORM_SIZE: this specifies that the file size was larger than the hidden field specified in your form.
    • UPLOAD_ERR_PARTIAL: this specifies that the file was not completely uploaded.
    • UPLOAD_ERR_NO_FILE: this specifies that the user did not select a file to upload.
    • UPLOAD_ERR_NO_TMP_DIR: this specifies that there was no temporary folder specified in your php.ini file


    so to recap if the file was uploaded without problems it checks to see if it is the right size, uploaded in full and was moved correctly.
    if there were errors then we get a read out of the errors it encountered.

    And thats it. We now have a functioning file upload script in its basic form. If you test the script and look in your uploads directory you will see the uploaded file.

    But what happens if someone uploads a file with the same name. Well in the part of the script that moves the file:

    Code:
    $destination = 'uploads/' . basename($_FILES['uploadedFile']['name']); // set the destination for where the file is to be transfered
    $moveIt = move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $destination);
    simply replace it with:

    Code:
    $time = time(); // get the current time stamp
    $destination = 'uploads/' . $time . basename($_FILES['uploadedFile']['name']); // set the destination for where the file is to be transfered
    $moveIt = move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $destination);
    this will add the current timestamp(seconds since Jan 1st 1970) to the beginning of the file name so there will never be duplicates.

    But what if you want only certain files uploaded? like images?

    well then:

    Code:
    $ext = strtolower(pathinfo($_FILES['uploadedFile']['name'], PATHINFO_EXTENSION));
    	  
    	  switch ($ext)
    	  {
    		case 'jpg': case 'jpeg': case 'png': case 'bmp': case 'gif':
    			break; // the file type is fine
    		default:
    			echo "File Type Not Allowed";
                            die;
    	  }

    This code needs to be added before you move the file.
    Basically we are getting the extension of the file via PATHINFO_EXTENSION then checking it to see if it is allowed.
    if it isnt then we are telling the user that it isnt. Using the die command after the check returns false means that the script will just stop working and not upload the file.

    If there is anything you would like made clearer then please ask and i will be happy to help

    Thanks
    Test and help out with a new
    100% open source forum package: A Simple Forum
    Check the A Simple forum Github Page
    Visit my Github profile to see what I work on.

  2. #2
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,301
    Mentioned
    460 Post(s)
    Tagged
    8 Thread(s)
    Nice tutorial. How does the hidden input element

    Code:
    <input type="hidden" value="999999999" name="maxSize" />
    set a file upload limit?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •