What are the best practices for storing and retrieving data from text files in PHP?

When storing and retrieving data from text files in PHP, it is important to follow best practices to ensure data integrity and security. One common approach is to use file handling functions like fopen, fwrite, and fread to interact with text files. It is also recommended to sanitize input data before writing it to a text file to prevent injection attacks. Additionally, using proper error handling techniques can help in detecting and resolving any issues that may arise during file operations.

// Open a text file for writing
$file = fopen("data.txt", "w");

// Sanitize and write data to the file
$data = "This is some data to be stored in the file.";
fwrite($file, $data);

// Close the file
fclose($file);

// Open the text file for reading
$file = fopen("data.txt", "r");

// Read data from the file
$data = fread($file, filesize("data.txt"));

// Close the file
fclose($file);

// Output the data
echo $data;