Monday 22 April 2013

PHP File


PHP File Handling

The fopen() function is used to open files in PHP.

Opening a File


The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:

<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>

·        The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.

·        Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.

·        When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong.

·        Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.

·        It is our hope that you will be able to avoid these and other slipups after reading this tutorial.

·        However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.
  

Closing a File


The fclose() function is used to close an open file.
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>

Reading a File Line by Line


The fgets() function is used to read a single line from a file.

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br>";
  }
fclose($file);
?>
  

Reading a File Character by Character


The fgetc() function is used to read a single character from a file.

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);
?>

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More