PHP
  Home arrow PHP arrow Page 4 - Defining a Custom Function for File Up...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Defining a Custom Function for File Uploaders with PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-04-09

    Table of Contents:
  • Defining a Custom Function for File Uploaders with PHP 5
  • The full source code of the previous file uploading application
  • Putting the file uploading script into the “uploadFile()” custom PHP function
  • Putting the uploadFile() PHP custom function to work

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    PCmover - $15 Off with Coupon Code CJPH7Q

    Defining a Custom Function for File Uploaders with PHP 5 - Putting the uploadFile() PHP custom function to work
    (Page 4 of 4 )

    In consonance with the concepts that I expressed in the prior section, the best way to demonstrate the capacity of the recently-defined “uploadFile()” function is by putting it to work in the context of a practical example. Therefore, suppose for a moment that I already coded a simple web form for letting users browse different files on their machines and uploading only one of them to the web server, like the one shown in the beginning of this tutorial.

    As you know, the sample (X)HTML that contains this online form would look like this:


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <title>Uploading files with PHP</title>

    <style type="text/css">

    body{

    padding: 0;

    margin: 0;

    background: #fff;

    }

    h1{

    font: bold 16pt Arial, Helvetica, sans-serif;

    color: #000;

    text-align: center;

    }

    p{

    font: normal 10pt Arial, Helvetica, sans-serif;

    color: #000;

    }

    form{

    display: inline;

    }

    #formcontainer{

    width: 50%;

    padding: 10px;

    margin-left: auto;

    margin-right: auto;

    background: #eee;

    border: 1px solid #666;

    }

    </style>

    </head>

    <body>

    <h1>Uploading files with PHP</h1>

    <div id="formcontainer">

    <form enctype="multipart/form-data" action="upload_file.php" method="post">

    <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />

    <p>File to upload <input name="userfile" type="file" />

    <input type="submit" name="send" value="Upload File" /></p>

    </form>

    </div>

    </body>

    </html>


    Now that I've coded the above file uploading web form, the only thing that remains undone is defining the pertinent “upload_file.php” file. This time it will include the definition of the previous “uploadFile()” custom function that you saw before.

    Given that, the aforementioned PHP file would now look like this:


    <?php

    // define 'uploadFile()' function

    function uploadFile($uploadDir='C:uploaded_files'){

    if(!is_dir($uploadDir)){

    throw new Exception('Invalid upload directory.');

    }

    if(!count($_FILES)){

    throw new Exception('Invalid number of file upload parameters.');

    }

    if(!in_array($_FILES['userfile']['type'],array
    ('image/jpeg','image/gif','image/png','text/plain','application/msword'))){

    throw new Exception('Invalid MIME type of target file.');

    }

    $uploadFile=$uploadDir.basename($_FILES['userfile']['name']);

    if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){

    return true;

    }

    // throw exception according to error number

    switch($_FILES['userfile']['error']){

    case 1:

    throw new Exception('Target file exceeds maximum allowed size.');

    break;

    case 2:

    throw new Exception('Target file exceeds the MAX_FILE_SIZE value specified on the upload form.');

    break;

    case 3:

    throw new Exception('Target file was not uploaded completely.');

    break;

    case 4:

    throw new Exception('No target file was uploaded.');

    break;

    case 6:

    throw new Exception('Missing a temporary folder.');

    break;

    case 7:

    throw new Exception('Failed to write target file to disk.');

    break;

    case 8:

    throw new Exception('File upload stopped by extension.');

    break;

    }

    }

    try{

    if($_POST['send']){

    // call 'uploadFile()' function

    if(uploadFile()){

    echo 'Target file uploaded successfully!';

    }

    }

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }

    ?>


    Did you realize how easy was to build a file uploading application using the “uploadFile()” PHP custom function listed previously? I’m sure you did! In this case, only two source files are required to get this application working. These can be quickly integrated into other existing PHP programs.

    All right, at this point, I've shown you how to create an extensible file uploading script that only uses a simple PHP custom function to work as expected. Of course, the script has plenty of room to be extended and improved, but this process, due to the intrinsic flexibility offered by the “uploadFile()” function, can be performed in an effortless way.

    Final thoughts

    That’s all for the moment. In this fourth part of the series, I taught you how to implement a highly-expandable file uploading application by way of a straightforward PHP 5 function that encapsulates all the logic required to perform this task in a few simple steps.

    And speaking of logic encapsulation, in the final tutorial of the series, I’ll show you how to construct a file uploading application similar to the one discussed before, but this time using a highly-modular PHP class.

    So, if you’re a strong advocate of using the object-oriented paradigm with PHP 5, you simply can’t miss this last article!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Over the course of this fourth part of the series, the file uploading application...
     

       

    PHP ARTICLES

    - Setting Up a Web-based Image Hosting Service
    - Comparing Files and Databases with PHP Bench...
    - Setting Up a Web-Based Image Gallery
    - Using Timers to Benchmark PHP Applications
    - Benchmarking Applications with PHP
    - Setting Up a Web-Based File Manager: PHPfile...
    - Developing a Modular Class For a PHP File Up...
    - Setting Up a Web-Based File Manager: bfExplo...
    - Defining a Custom Function for File Uploader...
    - Parsing Child Nodes with the DOM XML extensi...
    - Creating an Error Handling Module for a PHP ...
    - Accessing Attributes and Cloning Nodes with ...
    - Retrieving Information on Selected Files wit...
    - Handling HTML Strings and Files with the DOM...
    - Building File Uploaders with PHP 5

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway