18 File Handling – II

Hiren Joshi

epgp books

 

 

In the last topic, you have learned

  • How to get directory and file listing.
  • Reading an entire file
  • Writing to a file
  • Reading and writing a part of the file

 

In this session, you will be learning about

  • Read and Write a CSV data
  • Copy a file
  • Rename a file
  • Delete a file
  • Upload a file

 

Read and Write a CSV data

 

When you work with text file, you may use a text file – CSV file. CSV stands for Comma Separated Value. In CSV file, each line represents one record. Each record contains values which are separated by commas. The field values in CSV file contains comma, double quotes or line breaks, then these values must be enclosed in double quotes. CSV file is generally exported from spreadsheet or database tables and imported to create spread sheet or database tables.

 

A sample CSV file is shown below.

FH40,H5100,50000

4K72,UHD7200,125000

 

Functions to read from and write to CSV file

 

Function Description
fgetcsv($file) Retruns an array which contain a line of comma separated values
fputcsv($file,$array) Write $array into $file as a line of comma separated values

 

Following code shows how to write data into CSV file.

 

<?php

$cwd = getcwd();

$sep = DIRECTORY_SEPARATOR;

$name = ‘product.txt’;

$filename = $cwd.$sep.$name;

$products = array(array(‘p1′,’FHD40’,50000), array(‘p2′,’4K72’,125000));

$file = fopen($filename,’wb’);

foreach($products as $p)

{

fputcsv($file,$p);

}

fclose($file);

?>

 

The above code will write two records in the file product.txt

 

p1,FHD40,50000

p2,4K72,125000

 

The following code shows how to read the data from csv file.

 

<?php

$cwd = getcwd();

$sep = DIRECTORY_SEPARATOR;

$filename = ‘product.txt’;

$name = $cwd.$sep.$filename;

$file = fopen($name,’rb’);

while(!feof($file))

{

$line = fgetcsv($file);

if($line === false)

{

continue;

}

foreach($line as $v)

{

echo “$v “;

}

echo “<br>”;

}

fclose($file);

?>

 

The output is:

 

p1 FHD40 50000

p2 4K72 125000

 

Copy a file

 

When you are working with files, you may be required to copy a file. To copy a file copy function is used.

 

Function Description
copy($oldname, $newname)

 

Copies $oldname to $newname. If copy is successful, it returns

true.

 

 

Following code shows to copy a file.

 

<?php

$cwd = getcwd();

$sep = DIRECTORY_SEPARATOR;

$filename = ‘product.txt’;

$file = $cwd.$sep.$filename;

//   $file = ‘H:\wamp\www\PathshalaWAD\File Handling – II\product.txt’; $newname = ‘new copy product.txt’;

$c = copy($file,$newname); if($c === true)

{

echo “<br> File is copied successful”;

}

else

{

echo “<br> File is not copied successful”;

}

?>

 

The above code is copied a file product.txt as new copy product.txt.

 

Rename a file

 

To rename a file, you can use rename function.

 

Function Description
rename($oldname, $newname)

 

renames $oldname to $newname. If successful rename, it returns

true.

 

You can use, file_exists function to check whether the oldfile exists or not. It is a good practice to check whether a oldfile exists or not. If you don’t check and the file does not exist, PHP displays warning message. You should also check to make sure that newfile does not exists. In case, newfile exists, it will be overwritten by oldfile.

 

Delete a file

 

To delete a file, you can use unlink function.

 

Function Description
unlink($file) Delete the $file. If file is deleted successfully, returns true.

     <?php

$cwd = getcwd();

$sep = DIRECTORY_SEPARATOR;

$filename = ‘rename product.txt’;

$file = $cwd.$sep.$filename;

if(file_exists($file))

{

$success = unlink($file);

if($success === true)

{

echo “<br> File is deleted successfully”;

}

}?>

 

Upload a file

 

In a web application, generally it is required to upload a file to the web server. The file can be text file, image file, music file, XML file or video files. The file upload size varies according to web server. In WAMP 2.5 installation the maximum size for file upload is XX MB.

 

To upload a file you create a GUI using HTML. You have to use input tag and type attribute must be file. In the HTML form, method attribute value must be post and enctype attribute value must be multipart/form-data. When user click submit button of HTML form, the file is uploaded and server is saved the file as a temporary file. PHP can get the temporary file and move it to temporary location.

 

The autogloabl variable $_FILES stores information about each uploaded file.$_FILES is a nested array which stores each uploaded file in a array and a nested array store details of each uploaded file. For uploading, the temporary file is deleted when the script ends. $_FILES is a nested array which having following elements.

 

Key Description
name The original name of upload file
size Size in bytes of uploaded file
tmp_name Temporary name of the file uploaded on web server
type MIME type of upload file
error

 

Error code associated with file. The common values are

UPLOAD_ERROR_INI_SIZE (file size is very large)

UPLOAD_ERR_PARTIAL  (upload was not completed)

UPLOAD_ERR_OK (no error)

 

A function to save an uploaded file.

 

Function Description
Move_uploaded_file($tmp, $new)

 

Moves an uploaded file from temporary location to permanent

location. Returns true if file is moved successfully.

     HTML code to upload a file.

 

<html>

<body>

<form action=”upload.php” method=”post” enctype=”multipart/form-data”>

<input type=”file” name=”file1″>

<br>

<input type=”submit” name=”submit” value=”Upload”>

</form>

</body>

</html>

PHP code.

<?php

$temp = $_FILES[‘file1’][‘tmp_name’];

echo “<br> $temp”;

$cwd = getcwd();

$sep = DIRECTORY_SEPARATOR;

$path =$cwd.$sep;

$new = $path.$_FILES[‘file1’][‘name’];

$success = move_uploaded_file($temp,$new);

if($success)

{

echo “<br> File is uploaded successfully”;

}

else

{

echo “<br> File is not uploaded successfully”;

Exit();

}

?>

 

The output will be:

 

Temp : H:\wamp\tmp\phpE828.tmp

Upload file

File is uploaded successfully

you can view video on File Handling – II

References:

 

1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,

2. W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional, Apress

3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K. Glass:Beginning PHP5, Apache, and MySQL Web Development, Wrox,

4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media

5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove: Professional PHP, Wrox

6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible

7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach

8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications

9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams

10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide, Pearson Education

11. www.php.net

12. http://www.w3schools.com/

13. http://www.tutorialspoint.com/