The following code examples demonstrate the difference between Write-Only and Read-Write Mode in PHP.

In fact, both write-only (w) and read/write (w+) modes create a new file. In case, the file already exists, it is overwritten. However, the file opened in the mode ‘w’ can’t be read. Whereas, if we open it in ‘w+’ mode, then we can also read it.

The following code creates two files and writes some data to both of these files. Next, the value returned by the corresponding calls to the fread() function are assigned in the variables f1, and f2 respectively. However, the calls to the var_dump() method indicates that fread() returns the data only when the file is opened in the ‘w+’ mode.

<?php
// Creating a file 
  $text1=fopen("file1.txt", "w");
  $text2=fopen("file2.txt", "w+");
  $data1="Data in First File!";
  $data2="Data in Second File!";
  fwrite($text1, $data1);
  fwrite($text2, $data2);

  echo 'Contents of the first file...<br>';
  fseek($text1, 0);
  $f1=fread($text1, filesize('file1.txt'));
  var_dump($f1);
  echo '<br>Contents of the second file...<br>';
  fseek($text2, 0);
  $f2=fread($text2, filesize('file2.txt'));
  var_dump($f2);
?>

Output

The Difference Between Write-Only and Read-Write Mode in PHP
The Difference Between Write-Only and Read-Write Mode in PHP

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

programmingempire

princites.com