Could we help you? Please click the banners. We are young and desperately need the money
File handling is a fundamental part of backend development, and PHP provides a robust set of functions to manage files easily. Whether you're a junior developer learning the ropes or a senior developer refining your scripting skills, mastering CRUD operations on files is essential. In this guide, you'll learn how to Create, Read, Update, and Delete files using PHP.
PHP's file handling capabilities allow you to interact with the file system to perform operations like:
Before diving into each operation, it's good practice to understand file permissions and the environment your script is running in. Ensure that your PHP environment has the correct file permissions to avoid unexpected errors.
$filename = "sample.txt";
$file = fopen($filename, "w"); // 'w' for write mode (creates file if not exists)
if ($file) {
fwrite($file, "Hello, PHP file world!\n");
fclose($file);
echo "File created and data written successfully.";
} else {
echo "Error creating file.";
}
Contents of the created file:
$filename = "sample.txt";
if (file_exists($filename)) {
$file = fopen($filename, "r");
$content = fread($file, filesize($filename));
fclose($file);
echo nl2br($content);
} else {
echo "File does not exist.";
}
Output of the above function (if the file exists):
$filename = "sample.txt";
if (file_exists($filename)) {
$file = fopen($filename, "r");
while (!feof($file)) {
echo fgets($file) . "
";
}
fclose($file);
} else {
echo "File not found.";
}
$filename = "sample.txt";
$file = fopen($filename, "a"); // 'a' mode for appending
if ($file) {
fwrite($file, "This is new data appended to the file.\n");
fclose($file);
echo "Data appended successfully.";
} else {
echo "Failed to open file for appending.";
}
Contents of the file after updating it with "fopen()" and "fwrite()":
$filename = "sample.txt";
$newContent = "This replaces the previous content.\n";
file_put_contents($filename, $newContent);
echo "File content replaced.";
$filename = "sample.txt";
if (file_exists($filename)) {
unlink($filename);
echo "File deleted successfully.";
} else {
echo "File does not exist.";
}
Directory contents before the deletion of the file:
Directory contents after the deletion of the file:
Handling files in PHP is a crucial skill for developers working on data-driven or file-centric applications. Whether you're building a log system, generating reports, or processing user input, knowing how to Create, Read, Update, and Delete files efficiently sets the foundation for robust PHP development.
Stay consistent with best practices and always handle user data with security in mind. For more advanced file operations, explore PHP's SPL (Standard PHP Library) or file object handling classes.