File Handling in PHP
File handling in PHP allows you to read from and write to files on the server or manipulate file-related operations. Here are some common file handling operations in PHP:
file_get_contents
:<?php
// Read the entire contents of a file into a string
$content = file_get_contents("example.txt");
echo $content;
?>
fopen
, fread
, and fclose
:<?php
// Open the file in read mode
$handle = fopen("example.txt", "r");
// Read the file line by line
while (!feof($handle)) {
$line = fgets($handle);
echo $line;
}
// Close the file handle
fclose($handle);
?>
file_put_contents
:<?php
// Write a string to a file
$data = "Hello, World!";
file_put_contents("example.txt", $data);
?>
fopen
, fwrite
, and fclose
:<?php
// Open the file in write mode
$handle = fopen("example.txt", "w");
// Write data to the file
fwrite($handle, "Hello, World!");
// Close the file handle
fclose($handle);
?>
file_put_contents
with FILE_APPEND
flag:<?php
// Append a string to a file
$data = "New content to append";
file_put_contents("example.txt", $data, FILE_APPEND);
?>
fopen
, fwrite
, and fclose
with "a" mode:<?php
// Open the file in append mode
$handle = fopen("example.txt", "a");
// Write data to the end of the file
fwrite($handle, "New content to append");
// Close the file handle
fclose($handle);
?>
<?php
$filename = "example.txt";
// Check if a file exists
if (file_exists($filename)) {
echo "The file $filename exists.";
} else {
echo "The file $filename does not exist.";
}
?>
<?php
$filename = "example.txt";
// Check if the file exists before attempting to delete
if (file_exists($filename)) {
// Delete the file
unlink($filename);
echo "The file $filename has been deleted.";
} else {
echo "The file $filename does not exist.";
}
?>
These are basic examples, and it's important to handle file operations carefully, especially when dealing with user input or dynamic file names. Additionally, consider file permissions and security measures to protect against unauthorized access or manipulation of files.
Thank you.