php file handling

PHP File Handling

Create And Open File in PHP

$my_file = ‘file.txt’;
$handle = fopen($my_file, ‘w’) or die(‘Cannot open file: ‘.$my_file);

Write to a File in PHP

$my_file = ‘file.txt’;
$handle = fopen($my_file, ‘w’) or die(‘Cannot open file: ‘.$my_file);
$data = ‘Hello world www.nowaskme.com’;
fwrite($handle, $data);

Read a File in PHP

$my_file = ‘file.txt’;
$handle = fopen($my_file, ‘r’);
$data = fread($handle,filesize($my_file));

Append to a File

$my_file = ‘file.txt’;
$handle = fopen($my_file, ‘a’) or die(‘Cannot open file: ‘.$my_file);
$data = ‘This is data line 1′;
fwrite($handle, $data);
$new_data = “\n”.’this is data line 2’;
fwrite($handle, $new_data);

Close a File

$my_file = ‘file.txt’;
$handle = fopen($my_file, ‘w’) or die(‘Cannot open file: ‘.$my_file);
fclose($handle);

Delete a File

$my_file = ‘file.txt’;
unlink($my_file);