Writing Data To a File Using PHP

This article shows two ways to write data to a file. Also covered are some important file handling functions.

Introduction

This article explains how to write data to a file. In this article we also see all the ways to write data to the file such as binary-safe. There is basically the fwrite() function and the file_put_contents() function besides the PHP writing functions. I will also cover some of the useful file functions that are important to every programmer. 

Syntax of fwrite() function

int fwrite( resource $handle, string $str [, int $length])

The fwrite() function writes the contents of a string to the file stream pointed by the handle. 

handle 

handle is a file system pointer that is created by the fopen() function.

string

A string that is to be written.

length


The length parameter specifies where to stop writing after the length bytes written or the end of the string is reached, whichever comes first.

The fwrite() function returns the bytes in success, or FALSE on error.
 
The fread(), fwrite(), and fread() functions are all binary-safe. Binary-safe means we can use the contents of the file without worring about the contents (data) causing damage.

<?php

$file = 'C:\abc.TXT';
$fhandle = fopen($file'w'or die('Could not open file!');
fwrite(
$fhandle"hello world!"or die('Could not write to file');
fclose(
$fhandle);
?>

OutputOffreadfunction

Syntax of file_put_contents() function

int file_put_contents( string $filename, mixed $data[, int $flag=0 [, resource $context]] )

This function returns the number of bytes written to the file on success or FALSE on failure.

filename

filename is the path of the file where the contents are written. If filename does not exist then the file is created, otherwise the file is overwritten.

data

The data is the content to be written to the file. It can be a string, an array or a stream of resources.

flag


The following are some flags.

FILE_USE_INCLUDE_PATH

This flag will help to search in the include directory.

FILE_APPEND


If the file already exists then this flag will help to append the data to the file instead of overwriting.

LOCK_EX

Exclusive lock on the file when proceeding in the writing.
  
<?php
$file = 'C:\abc.TXT';
$fhandle = fopen($file'w'or die('Could not open file!');
fwrite(
$fhandle"hello world!"or die('Could not write to file');
fclose(
$fhandle);
?>

 file_put_contentsFunction 

Some Important File Handling functions

is_dir()
:  This function returns the boolean value if the specified path is a directory.
is_file(): This function returns a boolean value if the specified file is a regular file.
is_link(): This function returns a boolean value if the specified file is a symbolic link.
is_executable(): This function returns a boolean value if the specified file is a executable.
is_writable(): This function returns a boolean value if the specified file is a writable.
is_readable(): This function returns a boolean value if the specified file is a readable.
filesize(): This function returns the size file type.
filetime(): This function returns the last modification time of file.
filamtime(): This function returns the last access time of file .
fileowner(): This function returns the file owner.
filegroup(): This function returns the file group.
fileperms(): This function returns the file permission.
filetype() : This function returns the file type.

<!
DOCTYPE html>
<
html>
<
head>
       <
title></title>
 </
head>
     <
body>
    <
div style="width:330px;top:120pxleft:220px;position:relativeborder:1px solid graymargin-bottom:5pxpadding:5pxpadding-top:17px">
<?php
   
if (!isset($_POST['fileName'])) {
?>
  
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
      
Enter file path <input type="text" name="fileName">
  </
form>
<?php
}
else {
       
   echo 'File name: <b>'.$_POST['fileName']  .'</b><br />';
       
if (file_exists($_POST['fileName'])) {
          
echo 'File size: '.filesize($_POST['fileName']).' bytes<br />';
          
echo 'File owner: '.fileowner($_POST['fileName']).'<br />';
          
echo 'File group: '.filegroup($_POST['fileName']).'<br />';
          
echo 'File permissions: '.fileperms($_POST['fileName']).'<br />';
          
echo 'File type: '.filetype($_POST['fileName']).'<br />';
          
echo 'File last accessed on: '.date('Y-m-d', fileatime($_POST['fileName'])).'<br/>'
          
echo 'File last modified on: '.date('Y-m-d', filemtime($_POST['fileName'])).'<br/>'
      
if (is_dir($_POST['fileName'])) {
           
echo 'File is a directory <br />';
       }
      
if (is_file($_POST['fileName'])) {
          
echo 'File is a regular file <br />';
      }
      
if (is_link($_POST['fileName'])) {
          
echo 'File is a symbolic link <br />';
      }
      
if (is_executable($_POST['fileName'])) {
          
echo 'File is executable <br />';
      }
      
if (is_readable($_POST['fileName'])) {
          
echo 'File is readable <br />';
       }
      
if (is_writable($_POST['fileName'])) {
          
echo 'File is writable <br />';
       }
    }
     
else {
          
echo 'File does not exist!';
        }
}
?>  
</div>
</
body>
</html>
filetype
Summary

In this article we saw two ways to write data to a file. Also covered were some important file handling functions.