In PHP, file handling refers to reading from and writing to files on the server’s file system. PHP provides a variety of functions for performing file operations. Here’s an overview of how to work with files in PHP:
fopen() function, which takes two arguments: the file path and the mode (e.g., “r” for read, “w” for write, “a” for append).
$file = fopen("example.txt", "r") or die("Unable to open file!");fgets(), fgetc(), or fread().
// Read a line from the file $line = fgets($file); // Read a character from the file $char = fgetc($file); // Read the entire contents of the file $content = fread($file, filesize("example.txt"));fwrite().
$file = fopen("example.txt", "w") or die("Unable to open file!"); fwrite($file, "Hello, World!"); fclose($file);$file = fopen("example.txt", "a") or die("Unable to open file!"); fwrite($file, "Hello, World!"); fclose($file);fclose() function after you’re done with it to release system resources.
fclose($file);feof() function.
while (!feof($file)) { // Read lines from the file }unlink() function.
unlink("example.txt");chmod() function.
chmod("example.txt", 0644); // Read/write for owner, read for othersfilesize() function.
$size = filesize("example.txt");file_exists() function.
if (file_exists("example.txt")) { // File exists }These are some of the basic file handling operations you can perform in PHP. PHP’s file handling functions provide a flexible and powerful way to interact with files on the server’s file system, allowing you to read, write, and manipulate file contents as needed in your web applications.