PHP File Handling
PHP offers a wide range of functions and features for handling files and directories. In this guide, I'll cover basic file handling operations such as reading and writing files, working with directories, and handling file uploads.
Reading Files
Reading a File Line by Linephpy code
$file = fopen("example.txt", "r"); // Open the file for reading
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line; // Process each line
}
fclose($file); // Close the file when done
} else {
echo "Unable to open file!";
}
Reading the Entire File
php code
$file_contents = file_get_contents("example.txt"); // Read the entire file
echo $file_contents;
Writing Files
Writing to a File
php code
$data = "Hello, World!";
$file = fopen("example.txt", "w"); // Open the file for writing (creates if not exists)
if ($file) {
fwrite($file, $data); // Write data to the file
fclose($file); // Close the file
echo "Data written successfully!";
} else {
echo "Unable to open file for writing!";
}
Working with Directories
Creating a Directory
php code
$dir_name = "new_directory";
if (!is_dir($dir_name)) {
mkdir($dir_name); // Create a new directory
echo "Directory created!";
} else {
echo "Directory already exists!";
}
Listing Files in a Directory
php code
$dir = "/path/to/directory";
$files = scandir($dir); // Returns an array of filenames
foreach ($files as $file) {
echo $file . "<br>";
}
File Uploads
To handle file uploads in PHP, you typically use a form with enctype="multipart/form-data" and access the uploaded file information using the $_FILES superglobal.
HTML Form
html code
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_to_upload">
<input type="submit" value="Upload">
</form>
PHP File (upload.php)
php code
$target_dir = "uploads/"; // Directory where uploaded files will be stored
$target_file = $target_dir . basename($_FILES["file_to_upload"]["name"]);
$uploadOk = 1;
// Check if the file already exists
if (file_exists($target_file)) {
echo "File already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file_to_upload"]["size"] > 500000) {
echo "File is too large.";
$uploadOk = 0;
}
// Upload the file
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["file_to_upload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["file_to_upload"]["name"]) . " has been uploaded.";
} else {
echo "There was an error uploading your file.";
}
}
This is a basic overview of file handling in PHP, including reading and writing files, working with directories, and handling file uploads. Be sure to perform additional validation and security checks when working with user-uploaded files to ensure the security of your application.
Comments
Post a Comment