File Handling using PHP

Upload a file using PHP
private file handling with laravel

This solution will guide the method to modify/delete the contents of a text file using PHP.

solution 1.

Using file_put_contents:

file_put_contents($filename, 'file_content');

If you want to append to the file instead of replacing its contents use:

file_put_contents($filename, 'append_this', FILE_APPEND);

(file_out_contents is the simpler alternative to using the whole fopen complex.)

solution 2

if (is_writable($filename)) {
  if (!$handle = fopen($filename, 'w')) {
     echo "Cannot open file ($filename)";
     exit;
  }
  if (fwrite($handle, $somecontent) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
  }

  echo "Success, wrote to file ($filename)";

  fclose($handle);
}

Write “” to a file to delete its contents.

To delete contents line by line use:

$arr = file($fileName);

unset($arr[3]); // 3 is an arbitrary line

then write the file contents.

Upload a file using PHP
private file handling with laravel

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top