PHP File Handling (PFH)

In this section, we will learn how php scripts interact with files. As an example, we will continue the contact manager application by allowing users to upload photo files along with their comments. After the photos are successfully uploaded, we will provide a page to access the photos and comments.

Previously, the required HTML form must be prepared in the following form:

The form must be able to handle file uploads. The upload.htm code listing is as follows:

<html>

<head>
<title>Pic Uploader</title>
</head>

<body>

<h1>Pic Uploader</h1>
<form enctype="multipart/form-data" method="POST" action="upload.php">
  <p>Nama anda&nbsp; : <input type="text" name="nama">&nbsp;&nbsp; </p>
  <p>Masukkan foto anda&nbsp; : <input type="file" name="pic">&nbsp;&nbsp; </p>
  Komentar : <br><TEXTAREA ROWS=5 COLS=40 name="comment"></TEXTAREA>
  <p><input type="submit" value="Submit" name="B1"></p>
</form>

</body>

</html>

A. Writing files

Now we will work on the upload.php file which is useful for handling the upload file from the form. For example, we will fill in the form as follows:

The form, once filled and submitted, will be received by the server and produce the following variables:

| Nama Variabel | Keterangan                                                     | Isi                       |
|---------------|----------------------------------------------------------------|---------------------------|
| $nama         | Berisi tulisan yang diisikan user di textfield nama anda       | Endy Muhardin             |
| $comment      | Berisi tulisan yang diisikan user di textarea komentar         | Ini foto saya waktu kecil |
| $pic          | Berisi file gambar yang diupload, disimpan sementara di server | --                        |
| $pic_name     | Berisi nama file yang diupload                                 | Coffee Bean.bmp           |
| $pic_size     | Berisi ukuran file yang diupload                               | 16.6 kB                   |

We can display the above information in the upload.php script with the following code:

echo("Nama File User = $pic_name <br>");
echo("Nama File User di server= $pic <br>");
echo("Ukuran File User = $pic_size <br>");
echo("Jenis File User = $pic_type <br>");

The file we will write to the hard disk is in the $pic variable. We will copy this file to be stored permanently on the disk. To do this, we will add the following code to upload.php: 

$fileServer = "upload/$nama/$pic_name";
copy($pic, $fileServer);

In addition to the uploaded image file, we will also write the comments in the textarea into a file, with the same name as the image name, ending with the txt extension to mark that the file has a text format. To write into a file, do the following steps:

Open/create file  

To be able to access and change the contents of a file, we need a file descriptor. A file descriptor is a variable used to represent a particular file.

File descriptor is obtained by using the php function: fopen, to open the file. The file we will create will be named according to the image name. Add the following code to upload.php 

$fileComment = "/upload/$nama/$pic_name-comment.txt";
$fp = fopen($fileComment, "w");

As we see in the example above, we use the fopen function. This function requires two inputs (parameters), namely: file name, and access type.

  • File Name: string type, is the name of the file to be opened. Must be in the same folder as the php script that calls it.
  • Access Type: string type, determines the permitted treatment of the opened file. There are several types of access:
  • Read: symbolized by the letter r. The opened file can only be read and cannot be written to. Files opened with r access will generate an error message if an attempt is made to write to it.
  • Write: symbolized by the letter w. The opened file can only be written and cannot be read. Writing to the file will erase the previous contents.
  • Read and write: symbolized by r+. The opened file can be read and written. Writing to the file will be added to the beginning of the file.
  • Write and read: symbolized by w+. If the file already exists, its contents will be deleted.
  • Append: symbolized by a. Opening (creating if it does not exist) and writing at the beginning of the file. 
  • Append and read: symbolized by a+.
  • Opens (creates if it doesn't exist) and writes to the beginning of the file.
  • Binary mode. Symbolized by b. Used in Windows filesystems to differentiate between text and binary files.

Enter data 

After the file is successfully opened/created, enter data into it. The command is as follows:  

fwrite($fp, $comment);

Close file  

After that, close the file. 

fclose($fp);

B. Deleting files 

The uploaded file in the discussion above has been permanently stored on the server's hard disk in the upload/endymuhardin/Coffee Bean.bmp folder. Thus, we can delete files temporarily stored by the server. We delete the file using the unlink() or delete() command. Add the following line to upload.php. 

unlink($pic);

C. Create a directory 

Careful readers will notice that the folder names in the above examples are adjusted to the user name who uploaded the photo. Since we as programmers cannot predict the user name who will upload the photo, we cannot provide a folder that suits those needs. Thus, we must create folders dynamically. Creating a new directory or folder is not difficult, add the following line to upload.php :

$oldmask = umask(0);
mkdir("upload/$nama", 0777);
umask($oldmask);

The directory will be created with the folder name according to the user name entered in the form with permission 777. The meaning of permission 777 and umask is not discussed in this tutorial.

D. Directory navigation 

Next, we will display the photos that have been uploaded by the user. To do this, we must open the folder containing the files, see the list of existing files, and display the photos and comment content. To display the photos, we simply provide the link in the <img> </img> tag.

Meanwhile, to display the contents of a text file, we have to open and read the txt file.

To display the contents of a directory, we must first open the directory. Add the following code to upload.php : 

$myDir = "upload/$nama";
$dir = opendir($myDir);

The opened directory will be stored in the $dir variable.  

Next, we will loop to read each entry in the folder. Add the following code:  

echo("Isi folder upload/$nama : <br>");
while($tmp = readdir($dir)){
echo($tmp."<br>");
}

Once done, close the folder with the following code:

closedir($dir);

E. Deleting directories 

To delete a directory, use the following code:  

rmdir($namaDirektori);

The directory to be deleted must be empty.

F. Reading files 

To display the contents of the comments that we have written into a file, we will take the same steps as writing a file, namely: 

Open file -- read contents -- close file. 

There is a slight modification, we will process the contents of the comment so that it does not contain html tags. Add the following code to upload.php :

$f = fopen($fileComment, "r"); $isi = fread($f, filesize($fileComment)); fclose($f);
$output = nl2br(htmlspecialchars($isi)); echo("Komentar anda : <br>"); echo($output);

This is how the file contents are displayed.

The complete upload.php file is as follows:

<?
// -- Upload File -- //

// info tentang file user :  echo("Nama File User = $pic_name <br>"); echo("Nama File User di server= $pic <br>"); echo("Ukuran File User = $pic_size <br>"); echo("Jenis File User = $pic_type <br>");

// menulis file pic ke harddisk server
$oldmask = umask(0); mkdir("upload/$nama", 0777); umask($oldmask);
$fileGambar = "upload/$nama/$pic_name"; copy($pic, $fileGambar);

// menulis file comment ke file
$fileComment = "upload/$nama/$pic_name-comment.txt";
$fp = fopen($fileComment, "w"); fwrite($fp, $comment); fclose($fp);

// -- Menampilkan isi folder -- //

$myDir = "upload/$nama";
$dir = opendir($myDir);

echo("<hr>Isi folder upload/$nama : <br>"); while($tmp = readdir($dir)){   echo($tmp."<br>");
}
closedir($dir);

// -- menampilkan pic yang telah diupload -- // echo("<hr>Pic $nama : <br>");
echo("<img src=\"$fileGambar\" border=0 width=100 height=100>");

// -- menampilkan isi file text --//
echo("<hr>Komentar : <br>"); $f = fopen($fileComment, "r");
$isi = fread($f, filesize($fileComment)); fclose($f);
$output = htmlspecialchars($isi); echo($output);
?>

Post a Comment

Previous Next

نموذج الاتصال