PHP
  Home arrow PHP arrow Page 4 - Building File Uploaders with PHP 5
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 
 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

Building File Uploaders with PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2008-03-19

    Table of Contents:
  • Building File Uploaders with PHP 5
  • Implementing file uploads with PHP: the $_FILES superglobal array
  • Building a simple file uploading form
  • Processing a file upload with PHP

  • 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

    TestComplete™ automates software testing for a fraction of what the big guys charge. Easy functional and load testing for all Windows, .NET, Java and Web apps. Download a free trial now.

    Building File Uploaders with PHP 5 - Processing a file upload with PHP
    (Page 4 of 4 )

    Handling a file upload with PHP is a much simpler process than you might think. The core logic that must be implemented to perform this process is simply moving the user file that resides on a temporary directory of the web server to its final location.

    Of course, as with many things in PHP programming, there are several ways to accomplish a file upload and each of them generally involves the use of different PHP native functions. However, in this particular case, I'm going to use the "move_uploaded_file()" function, which moves an uploaded file to a new location in the web server.

    In simple terms, this function verifies that the target file has been uploaded by way of an HTTP POST request. And if this condition is true, the file in question is moved to the final location.

    Now that you have a clear idea of how the "move_uploaded_file()" function works, pay close attention to the following PHP script. It uses this function to move an uploaded file to a predefined directory in the web server:


    // basic example on uploading a file to the server via HTTP
     

    if($_POST['send']){

    // set upload directory (for Windows users)

    $uploadDir='C:uploaded_files';

    // set destination of uploaded file

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

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

    echo 'The target file was successfully uploaded!';

    }

    else{

    echo 'Error uploading target file!';

    }

    }


    If you study the above PHP script in detail, you'll understand how it works. Basically, it checks to see if the corresponding file uploading form has been submitted and uses the aforementioned "move_uploaded_file()" PHP built-in function to move the uploaded file from its temporary directory to a predefined location in the web server.

    In this case, I decided to move all of the valid uploaded files to the "C:uploaded_files" directory, which obviously is valid only for Windows users. If you're using another operating system, this option can be modified to fit your specific requirements.

    Finally, if the uploaded file can't be moved to the predefined directory, a trivial error message is displayed on the browser. Of course, one of the most important things to highlight concerning the definition of the previous PHP script is the way that some elements of the $_FILES superglobal PHP array are utilized to complete the pertinent file uploading process. Now do you realize how the different pieces fit with each other when it comes to uploading files with PHP? I bet you do!

    In addition, I'd like to wrap up this tutorial by showing you the complete source code of the two files that compose this basic file uploading PHP application so you can examine them more easily. Here they are:


    (definition of 'upload_form.htm' file)


    <!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="20000" />

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

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

    </form>

    </div>

    </body>

    </html>



    (definition of 'upload_file.php' file)


    if($_POST['send']){

    // set upload directory (for Windows users)

    $uploadDir='C:uploaded_files';

    // set destination of uploaded file

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

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

    echo 'The target file was successfully uploaded!';

    }

    else{

    echo 'Error uploading target file!';

    }

    }


    Before starting to upload files with PHP, remember to check your php.ini settings in addition to assigning the appropriate permissions to the corresponding destination directory in the web server.

    Final thoughts

    In this first tutorial of the series, I showed you how to build a basic file uploading application with PHP. It's something that can be useful if you're just starting to use this handy language or if you want to fill some possible gaps with reference to this topic.

    However, when it comes to handling file uploads with PHP, I'm only scratching the surface. The application that I developed earlier lacks some important features, such as adequate control over the type and size of the file being uploaded as well as the inclusion of a solid error handling module.

    Of course, all of these issues will be addressed in the next part. So you don't have any excuses to miss it!


    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.

       · Uploading files to a server using a web-based interface has always been an...
       · HelloI used scripts as the presented in the article to catch file uploads not from...
       · Hi Gustavo,Thank you for commenting on my PHP article. With reference to your...
       · Thank you for answer. Im sure I've took care about some of the things you mentioned,...
       · Hi again Gustavo,It seems there’s a problem with different settings for PHP 4...
       · ThanksI just do test using a full path as...
       · Thanks for the comments and I hope you can fix up your problem.Regards.
       · I found the solution, I post it here for anybody:The issue was: "there are a...
       · I’m glad to know you found the solution. And surely, it will be useful for other...
     

       

    PHP ARTICLES

    - 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
    - Working with Multiple Document Nodes with th...




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