PHP
  Home arrow PHP arrow Page 7 - File And Directory Manipulation In PHP (part 2)
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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: starstarstarstarstar / 65
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    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

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT