Home arrow PHP arrow Page 7 - File And Directory Manipulation In PHP (part 2)

Beam Me Up - PHP

Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.

TABLE OF CONTENTS:
  1. File And Directory Manipulation In PHP (part 2)
  2. Stripping It To The Bone
  3. Fertile Fields
  4. Configuring The System
  5. The Right Path
  6. Move It
  7. Beam Me Up
  8. Diving Into Directories
  9. A Pattern Emerges
  10. Purging The Dead
  11. Size Does Matter
  12. In Process
  13. Disk Full
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 65
August 21, 2003

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: