php provide all type of file operation. Let us check some of the Basic PHP File Operations like Create a File, Open a File, Write to a File, Append to a File, Close a File, Delete a File, Rename a File, Reading a File Line by Line, Reading a File Character by Character etc..
Before that we can check what are the diffrent mode of opening a file.
w : Open for writing only.
r : Open file for reading only.
r+ : Open file for reading and writing.
w+ : Open file for reading and writing.
a : Open file for writing only.
a+ : Open file for reading and writing.
x : Create and open file for writing only.
x+ : Create and open file for reading and writing.
c : Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated.
c+ : Open the file for reading and writing.
Open a File
$open_file_name = 'file.txt'; // add file link
$handle = fopen($open_file_name, 'w') or die('Some error in Opening the File: '.$open_file_name);
//open file
$handle = fopen($open_file_name, 'w') or die('Some error in Opening the File: '.$open_file_name);
//open file
Write to a File
$file_name = 'file.txt'; //add file location
$handler = fopen($file_name, 'w') or die('Some error in Opening the File: '.$file_name); //open file
$data = 'This is the data'; /add data
fwrite($handler, $data); //write to file
fclose($handler); //close file
$handler = fopen($file_name, 'w') or die('Some error in Opening the File: '.$file_name); //open file
$data = 'This is the data'; /add data
fwrite($handler, $data); //write to file
fclose($handler); //close file
Append to a File
$file_name = 'file_name.txt';
$handler = fopen($file_name, 'a') or die('Some error in Opening the File: '.$file_name);
$data = 'This is Line No 1';
fwrite($handler, $data);
$new_append_data = "\n".'This is Line No 2'; //append data
fwrite($handler, $new_append_data);
fclose($handler);
$handler = fopen($file_name, 'a') or die('Some error in Opening the File: '.$file_name);
$data = 'This is Line No 1';
fwrite($handler, $data);
$new_append_data = "\n".'This is Line No 2'; //append data
fwrite($handler, $new_append_data);
fclose($handler);
Close a File
$file_name = 'file.txt';
$handler = fopen($file_name, 'w') or die('Some error in Opening the File: '.$file_name);//other file operations goes here.
fclose($handler);
$handler = fopen($file_name, 'w') or die('Some error in Opening the File: '.$file_name);//other file operations goes here.
fclose($handler);
Delete a File
$file_name = 'file.txt';
unlink($file_name);
unlink($file_name);
Rename a File
rename($old_file_name, $new_file_name);
No comments:
Post a Comment