PHP
  Home arrow PHP arrow Page 7 - File And Directory Manipulation In PHP...
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

File And Directory Manipulation In PHP (part 2)
By: icarus, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 59
    2003-08-21

    Table of Contents:
  • File And Directory Manipulation In PHP (part 2)
  • Stripping It To The Bone
  • Fertile Fields
  • Configuring The System
  • The Right Path
  • Move It
  • Beam Me Up
  • Diving Into Directories
  • A Pattern Emerges
  • Purging The Dead
  • Size Does Matter
  • In Process
  • Disk Full

  • 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    File And Directory Manipulation In PHP (part 2) - Beam Me Up
    (Page 7 of 13 )

    Most often, you'll find yourself using rename(), copy() and unlink() functions in the context of files uploaded to PHP via a Web browser - so-called "HTTP file uploads". Consider the following example, which
    demonstrates:


    <html>
    <head>
    </head>

    <body>

    <?php
    if (!$_POST['submit'])
    {
    ?>
    <form enctype="multipart/form-data" action="<?=$_SERVER['PHP_SELF']?>"
    method="post">
    Description:
    <br>
    <input type="Text" name="desc" size="40">
    <p>
    File:
    <br>
    <input type="file" name="file">
    <p>
    <input type="submit" name="submit" value="Add Image">
    </form>
    <?
    }
    else
    {

    // validate form data
    if ($_FILES['file']['size'] == 0) { die("Bad upload!"); }

    if ($_FILES['file']['type'] != "image/gif" && $_FILES['file']['type'] != "image/jpeg" && $_FILES['file']['type'] !=
    "image/pjpeg") { die("Invalid file format!"); }

    if (!$_POST['desc']) { die("No description!"); }

    // open connection to database
    $connection = mysql_connect("localhost", "root", "secret") or die ("Unable to connect!");
    mysql_select_db("db1") or die ("Unable to select database!");

    // formulate and execute query
    $query = "INSERT INTO gallery (dsc) VALUES ('" . $_POST['desc']. "')";
    $result = mysql_query($query) or die("Error in query: " . mysql_error());
    $id = mysql_insert_id($connection);

    // get file type and rename file to recordID.ext
    if ($_FILES['file']['type'] == "image/gif") { $ext = ".gif"; }
    if ($_FILES['file']['type'] == "image/jpeg") { $ext = ".jpg"; }
    if ($_FILES['file']['type'] == "image/pjpeg") { $ext = ".jpg"; }

    $newFileName = $id . $ext;

    // copy file to new location
    copy($_FILES['file']['tmp_name'], "/mydatadir/" . $newFileName);

    // update database with new file name
    $query = "UPDATE gallery SET filename = '$newFileName' WHERE id = '$id'";
    $result = mysql_query($query) or die("Error in query: " . mysql_error());

    }
    ?>
    </body>
    </html>

    In this case, when a file is uploaded, it is automatically stored in a temporary directory by PHP, and its temporary filename is exposed via the "tmp_name" key of the $_FILES array. A copy() function can then be used to copy the uploaded file from its temporary location to its new location, and it can also be renamed along the way if needed (as in the above example). Once the script finishes executing, the temporary file is automatically deleted by PHP.

    Since file uploads are fairly common in PHP, the language also offers two specialized functions designed specifically to assist you in the process of handling such uploaded files: the is_uploaded_file() function, which tests if a file was uploaded via the HTTP POST method, and the
    move_uploaded_file() function, which is used to move an uploaded file to a new location after verifying its integrity. Here is a rewrite of the previous example using these functions, in order to better illustrate how they can be used:


    <html>
    <head>
    </head>

    <body>

    <?php
    if (!$_POST['submit'])
    {
    ?>
    <form enctype="multipart/form-data" action="<?=$_SERVER['PHP_SELF']?>"
    method="post">
    Description:
    <br>
    <input type="Text" name="desc" size="40">
    <p>
    File:
    <br>
    <input type="file" name="file">
    <p>
    <input type="submit" name="submit" value="Add Image">
    </form>
    <?
    }
    else
    {

    // validate form data
    if ($_FILES['file']['size'] == 0) { die("Bad upload!"); }

    if ($_FILES['file']['type'] != "image/gif" && $_FILES['file']['type'] != "image/jpeg" && $_FILES['file']['type'] !=
    "image/pjpeg") { die("Invalid file format!"); }

    if (!$_POST['desc']) { die("No description!"); }

    if (!is_uploaded_file($_FILES['file']['tmp_name'])) { die("Bad file!"); }

    // open connection to database
    $connection = mysql_connect("localhost", "root", "secret") or die ("Unable to connect!");
    mysql_select_db("db1") or die ("Unable to select database!");

    // formulate and execute query
    $query = "INSERT INTO gallery (dsc) VALUES ('" . $_POST['desc']. "')";
    $result = mysql_query($query) or die("Error in query: " . mysql_error());
    $id = mysql_insert_id($connection);

    // get file type and rename file to recordID.ext
    if ($_FILES['file']['type'] == "image/gif") { $ext = ".gif"; }
    if ($_FILES['file']['type'] == "image/jpeg") { $ext = ".jpg"; }
    if ($_FILES['file']['type'] == "image/pjpeg") { $ext = ".jpg"; }

    $newFileName = $id . $ext;

    // move file to new location
    move_uploaded_file($_FILES['file']['tmp_name'], "/mydatadir/" .
    $newFileName) or die("Could not move file!");

    // update database with new file name
    $query = "UPDATE gallery SET filename = '$newFileName' WHERE id = '$id'";
    $result = mysql_query($query) or die("Error in query: " . mysql_error());

    }
    ?>
    </body>
    </html>

    More PHP Articles
    More By icarus, (c) Melonfire


     

       

    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 1 hosted by Hostway