codescracker


php

PHP File I/O



« Previous Tutorial Next Tutorial »


You are free to handle file on the web using PHP. You can perform these types of actions on files using PHP:

Opening a File in PHP

You are free to use fopen() function in PHP to open a file. Here is an example, opening a file using PHP:

fopen(filename, "filemodes");

File Modes in PHP

Here the following table lists the filemodes available in PHP:

Mode Meaning
w Opens a file for writing only. Creates a new file, if not exist
w+ Opens a file for reading and writing both. Creates a new file, if not exist
r Opens a file for reading only
r+ Opens a file for reading and writing both
a Opens a file for appending only. Creates a new file, if not exist
a+ Opens a file for reading and appending both. Creates a new file, if not exist

Closing a File in PHP

To close a file in PHP, use fclose() function. Here is an example, closes a file using fclose() in PHP:

fclose(filename);

Reading a file in PHP

To read a file, use fread() function. Here are the steps required in reading a file in PHP:

The following example assigns the content of a text file to a variable and then displays those contents on the web page :

<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>

<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
   echo ( "Error in opening file" );
   exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

</body>
</html>

Writing to file using PHP

Here is an example showing how to write some content to a file using fwrite() function in PHP:

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

<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>

<?php
if( file_exist( $filename ) )
{
   $filesize = filesize( $filename );
   $msg = "File created with name $filename ";
   $msg .= "containing $filesize bytes";
   echo ($msg );
}
else
{
   echo ("Sorry! File $filename does not exit" );
}
?>
</body>
</html>

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test