Friday, March 13, 2015

Working with files , files I/O (input/output)

 In PHP fopen() function  is used to open a file. Two arguments are to be passed stating first the file name and then mode in which to operate.

Syntax:

<?php
io_function(argument1,argument2);
?>
 File modes are specified with six option:



Mode
Purpose
r
Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+
Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w
Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
w+
Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
a
Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
a+
Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.


How to read from a file?

Once a file is opened using  fopen() function now it can be read with a function called fread(). This function also requires two arguments.



Example:

PHP Script (fileread.php)

<html>
<head>
<title>nirajanghimirey's workshop</title>
</head>
<body>
<h1>Reading file via  PHP</h1>
<?php
$filename = "new_file.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );
echo "This is reading $filename and size of this file is $filesize byte.";
echo "<pre>$filetext</pre>";
?>
</body>
</html>


How to write a file?

You can write a new file or you can append text file to an existing file using the PHP fwrite() function. This function requires two argument specifying a file pointer and the string of data that is to be written.

Example :

PHP Script (file_write.php)

<?php
$filename = "new_file.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is  a simple test\n" );
fclose( $file );
?>

<html>
<head>
<title>nirajanghimirey's workshop</title>
</head>
<body>
<h1>Writing a file using PHP</h1>
<?php
if(file_exists( $filename ) )
{
   $filesize = filesize( $filename );
echo "Filehas been created with name $filename and having size $filesize byte.";
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>

No comments:

Post a Comment