PHP File Handling

Learn how to work with files in PHP, including reading, writing, and managing file operations.

Introduction to PHP File Handling

PHP provides various functions to handle files, allowing you to create, read, write, and delete files on the server. This is essential for many web applications, such as logging, storing user data, or serving downloadable content.

Basic File Operations

The most common file operations include:

  • Opening files
  • Reading files
  • Writing files
  • Closing files

Opening a File

You can open a file using the fopen() function. This function returns a file pointer that you can use for further file operations.

<?php
$file = fopen("example.txt", "r"); // Open the file for reading
?>

Reading a File

To read from a file, you can use functions like fgets(), fread(), or file_get_contents().

<?php
$content = fread($file, filesize("example.txt")); // Read the entire file
echo $content;
fclose($file); // Close the file after reading
?>

Writing to a File

To write data to a file, you need to open it in write mode using "w" or append mode using "a". Then, you can use fwrite() to write data.

<?php
$file = fopen("example.txt", "a"); // Open the file for appending
fwrite($file, "Hello, World!\n"); // Write to the file
fclose($file); // Close the file after writing
?>

Closing a File

Always close the file after completing the operations using fclose().

File Uploads

PHP allows users to upload files to the server. The uploaded file can be handled using the $_FILES superglobal.

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload">
    <input type="submit" value="Upload">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $target_file = "uploads/" . basename($_FILES["fileToUpload"]["name"]);
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file); // Move uploaded file
}
?>

File Permissions

When working with files, ensure that the server has the appropriate permissions to read or write files. You can check or change file permissions using the chmod() function.

<?php
chmod("example.txt", 0644); // Set permissions to read and write for owner, read for others
?>

Conclusion

PHP file handling is a powerful feature that enables developers to manage files efficiently. Understanding how to read, write, and upload files is essential for building dynamic web applications.