Uploading Files and Navigating Directories in PHP

In this article we are going to look at how to upload files and also how to navigate through directories. It is the second part of a tutorial that began last week with “Reading, Writing, and Creating Files in PHP.”

Code

For file uploading to work, it must be turned on in your php ini file. And the upload _tmp_dir must be set; in other words the upload directory must exist.

Below is an extract from a php ini file:

;;;;;;;;;;;;;;;;

; File Uploads ;

;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.

file_uploads = On

; Temporary directory for HTTP uploaded files (will use system
default if not

; specified).

upload_tmp_dir = C:PHPuploadtemp  ; temporary directory for
HTTP uploaded files (will use system default if not specified)

; Maximum allowed size for uploaded files.

upload_max_filesize = 2M

*****End php.ini file*****

Here you can see that all the necessary settings are made.

Once you’ve made all the necessary changes to your php settings, let’s create the form needed to do the uploads. To enable a form to handle uploads, you need to change three things on a standard form.

  • First, the initial form line must include enctype=”multipart/form-data.” This tells the browser to expect different types of data.
  • Second, a hidden input type should be included to tell the browser the max file size allowed for uploading. This is not strictly necessary, as users may upload files of varying sizes.
  • Third, the “<input name=”userfile” type=”file”>” is included to create the upload field and also creates the browse button. Below is an example of a upload form.

Fig1. Upload form example

PHP fills a $_FILES[''] array with information about the file that you upload. The array contains the following info:

Name – name of the file as it was on the local disk.

Type – mime type of the file (example image/gif).

Size – file size.

Tmp_name- name of the file as it is stored in the final destination.

Error – error code for when something goes wrong.

Code

Meaning

0

No Error

1

File exceeds set upload_max_filesize

2

File exceeds the max_file_size setting in form

3

File was partially uploaded

4

No file was uploaded

{mospagebreak title=Uploading files}

When a file is uploaded, it is first placed in a temporary directory. You have to use the move_uploaded_file() function to move it to its final destination. The move_uploaded_file function takes three parameters:

move_uploaded_file($_FILES['userfile']['tmp_name'],
‘/upload/to/path/’. $filename);

To demonstrate, create a normal HTML  form, and make the changes we’ve discussed to turn it into a upload form. Below is a example:

<html>
<head>
  <title>Administration – upload new files</title>
</head>
<body>
<p>Upload File</p>
<form enctype=”multipart/form-data” action=”upload.php”
method=”post”>
  <input type=”hidden” name=”MAX_FILE_SIZE” value=”1000000″>
  Upload this file: <input name=”userfile” type=”file”><br>
  <input type=”submit” value=”Upload File”>
</form>
</body>
</html>

Now let’s create a script to handle the uploaded file:

Script: do_upload.php
<?
//define the upload path
$uploadpath = “c:uploads”;
//check if a file is uploaded
 if($_FILES['userfile']['name']) {
  $filename = trim(addslashes($_FILES['userfile']['name']));
//move the file to final destination
  if(move_uploaded_file($_FILES['userfile']['tmp_name'],
$uploadpath.”/”. $filename)) {
  echo “The file has been uploaded”;
  } else{
    if ($_FILES['userfile']['error'] > 0)
  {
       switch ($_FILES['userfile']['error'])
    {
      case 1:  echo ‘File exceeded upload_max_filesize';  break;
      case 2:  echo ‘File exceeded max_file_size';  break;
      case 3:  echo ‘File only partially uploaded';  break;
      case 4:  echo ‘No file uploaded';  break;
    }
    exit;
  }
  }
}
?>

The do_upload script first sets the upload path by declaring

‘$uploadpath = “c:uploads”;

This is where our files are going to be stored on our C drive. Next we check to see whether the Files array is filled:

‘ if($_FILES['userfile']['name']) {‘

If it is filled, the ‘move_upload_file()‘ function is used to upload the file and a message is shown. In case the array is not filled we define a switch statement with the various error numbers and what they mean:

      case 1:  echo ‘File exceeded upload_max_filesize';  break;
      case 2:  echo ‘File exceeded max_file_size';  break;
      case 3:  echo ‘File only partially uploaded';  break;
      case 4:  echo ‘No file uploaded';  break;

One of these errors will be executed when an error number is found in the File array.

Here’s a screen shot of both scripts in action:

Fig2. A file is selected for uploading…

 

Fig3. File upload message…

{mospagebreak title=Multiple file uploads}

Uploading multiple files simultaneously is not very different from uploading a single file. All you need to do is use a different name for each file that you want to use:

<form enctype=”multipart/form-data” action=”do_upload.php”
method=”post”>  Upload files:

<input name=”Afile[]” type=”file” size=”80″>
<input name=”Afile[]” type=”file” size=”80″>
<input name=”Afile[]” type=”file” size=”80″>
  <br>
  <input type=”submit” value=”Upload File”>
</form>

When the above form is submitted, the arrays $_FILES['Afile'], $_FILES['A']['name'], and $_FILES['Afile']['size'] will be initialized and all of them will be numerically indexed. For example say you submit three files with the names uploader.html, fileprocess.php and what.php. The $_FILES['Afile']['name'][0] array will contain uploader.html and the  $_FILES['Afile']['name'][1] array will contain what.php, and so on. All of the file attributes such as size and name will be available for each file that you submitted.

Once you’ve submitted the form you simply do a “for each” loop and display the form information.

Another way in which you can upload multiple files is by explicitly giving the “name” part of the form input a different name:

<form enctype=”multipart/form-data” action=”do_upload.php”
method=”post”>  Upload files:

<input name=”Afile1″ type=”file” size=”80″>
<input name=”Afile2″ type=”file” size=”80″>
<input name=”Afile3″ type=”file” size=”80″>
  <br>
  <input type=”submit” value=”Upload File”>
</form>

And then process them as normal.

Create another HTML document and call it uploaderfrm.html. Add the following code:

Uploader.html

<html>
<head>
<title>HTML Form for Multiple File Uploading</title>
</head>
<body>
<p>Multiple File Upload</p>
<br />
<form action=”uploader_do.php” method=”post”
enctype=”multipart/form-data”>
<p>Files:<br>
<input type=”file” name=”AFile[]” /><br>
<input type=”file” name=”AFile[]” /><br>
<input type=”file” name=”AFile[]” /><br>
<input type=”submit” value=”Upload Files” />
</p>
</form>
</body>
</html>

Now, let’s create the script that will handle form data. Create a new PHP Document and save it as uploader_do.php.

Script:uploader_do.php

<?php

$uploaddir=”c:uploads”;
if(isset($_FILES['AFile']['error'])){ 
   foreach ($_FILES["AFile"]["error"] as $key => $error) { 
      if ($error == UPLOAD_ERR_OK) { 
         $tmp_name = $_FILES["AFile"]["tmp_name"][$key]; 
         $name = $_FILES["AFile"]["name"][$key]; 
         move_uploaded_file($tmp_name, $uploaddir. “/” .$name); 
      } 
   }

?>

As with our previous upload script, first we define where we want to store the uploaded files by declaring ‘$uploaddir=”c:uploads”;’ From this declaration we can see that our files are going to be stored on our C drive. Next we check whether there are any errors in the submitted File array:

if(isset($_FILES['AFile']['error'])){

If there are any errors, the files will not be uploaded. If on the other hand there are no errors, the files are uploaded by the ‘move_upload_file()‘ function.

There’s another way that you can dynamically create input fields on a form to upload files. If you present a user with a form asking how many files he or she wants to upload, once you have the number you can simply create a dynamic form with n number of input tags and continue from there.

{mospagebreak title=Navigating Directories}

Before we start with the next section, please make sure that you are familiar with file permissions. Pretty much everything in the File Permissions section applies to the directories. To navigate through a directory, you begin by opening the directory with opdir() function:

$dir = opendir(‘directoryname’);

As with reading and writing files, you create a pointer that can be referenced by the opened directory. To read the list of files within a directory you use the readdir() function, in a while loop:

while($thedir=readdir($dir)){
//write the file details here
}

and then you finally close the open directory with the closedir() function:

closedir($dir);

Other functions that we are going to use include:

 filesize() function – gives you the size of  the file in bytes.

filetime() – retrieves the modification time of a file.

Both of these functions are going to help us to create a directory listing.

Let’s build a script that will show us the insides of a directory listing:

Script: browsedir.php

This script will list file names, file size and modification dates:

<html>
<head>
  <title>Browse Directories</title>
</head>
<body>
<p>Browsing</p>
<?php
  $current_dir = ‘.';
  $dir = opendir($current_dir);
echo “Current directory is <b>$current_dir</b><br />”;
echo’ <table width=”100%” border=”0″ cellspacing=”1″>
  <tr>
    <td width=”34%”><b>File Name</b> </td>
    <td width=”26%”> <b>File Size </b></td>
    <td width=”40%”><b>Last Modified</b> </td>
  </tr>';
  while ($file = readdir($dir))
  {
  $fs=filesize($file);
  $moddate=date(‘F j, Y’,filemtime($file));
echo ‘ <tr>
    <td>’.$file.'</td>
    <td>’.$fs. ‘ bytes</td>
    <td>’.$moddate.'</td>';              

  }
   closedir($dir);
?>
  </tr>
  </table>
</body>
</html>

Fig5. Shows a list of all the files in the current directory, represented here by a dot(.) 

Conclusion

This concludes our file and directory handling exploration. 

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye