Files in PHP
Files in PHP
For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.
Read: 'r' Open a file for read only use. The file pointer begins at the front of the file.
Write: 'w' Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. The file pointer begins at the start of the file.
Append: 'a' Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.
Read/Write: 'r+' Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
Write/Read: 'w+' This is exactly the same as r+, except that it deletes all information in the file when the file is opened.
Append: 'a+' This is exactly the same as r+, except that the file pointer is at the end of the file.
Create a File
Open a File
$my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //open file for writing ('w','r','a').
Read a File
Write to a file
$my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); $data = 'This is the data'; fwrite($handle, $data);
Append to a File
$my_file = 'file.txt'; $handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file); $data = 'New data line 1'; fwrite($handle, $data); $new_data = "\n".'New 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); //write some data here fclose($handle);
Delete a file