File handling in PHP involves reading from and writing to files, managing file uploads, and setting file permissions. These capabilities are essential for many web applications.

Reading from and Writing to Files

  • Opening a File: Use fopen() to open a file for reading or writing.
  $file = fopen("example.txt", "r"); // Open file for reading
  
  • Reading from a File: Use functions like fread(), fgets(), or file_get_contents() to read data from a file.

  • Read Entire File:

  $content = file_get_contents("example.txt");
  
  • Read Line by Line:
  while (($line = fgets($file)) !== false) {
    echo $line;
}
  
  • Writing to a File: Use fwrite() to write data to a file. Open the file with the "w" or "a" mode to write or append data, respectively.

    • Write Data:
      $file = fopen("example.txt", "w");
    fwrite($file, "Hello, World!");
    fclose($file);
      
  • Closing a File: Always close the file with fclose() after finishing operations.

  fclose($file);
  

File Uploads

Handling file uploads involves managing files submitted via HTML forms.

  • HTML Form for File Upload:
  <form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload">
    <input type="submit" value="Upload File">
</form>
  
  • Handling File Uploads in PHP: Use the $_FILES superglobal to access uploaded files.
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
  
  • File Upload Restrictions:

    • File Size: Set upload_max_filesize and post_max_size in php.ini.
    • Allowed Types: Validate the file type using $_FILES['fileToUpload']['type'].

File Permissions

File permissions determine who can read, write, or execute a file.

  • Changing File Permissions: Use chmod() to change file permissions.
  chmod("example.txt", 0644); // Set read and write for owner, read-only for others
  
  • Checking File Permissions: Use is_readable(), is_writable(), and is_executable() to check permissions.
  if (is_writable("example.txt")) {
    echo "The file is writable.";
}
  
  • File Ownership: Change file ownership using chown() and chgrp() functions, but this typically requires appropriate permissions and is not always possible in shared hosting environments.

File handling in PHP enables you to interact with the file system, manage user uploads, and control file access. Properly handling files ensures your application can store and retrieve data efficiently and securely.