PHP File Handling

PHP File Handling refers to the ability to work with files on the server using PHP. PHP provides a variety of functions for handling files, such as reading, writing, uploading, and deleting files. Here are some examples of how to use PHP’s file handling functions:

  1. Reading a file:
$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line;
    }
    fclose($file);
}
  1. Writing to a file:
$file = fopen("example.txt", "w");
if ($file) {
    fwrite($file, "This is some text that will be written to the file.");
    fclose($file);
}
  1. Uploading a file:
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tmp_name = $_FILES['file']['tmp_name'];
    $name = basename($_FILES['file']['name']);
    move_uploaded_file($tmp_name, "uploads/$name");
}
  1. Deleting a file:
if (file_exists("example.txt")) {
    unlink("example.txt");
}

These are just a few examples of PHP’s file handling functions. PHP also provides functions for working with directories, creating and deleting files, copying and moving files, and more. By using PHP’s file handling functions, developers can create more dynamic and powerful web applications that can interact with files on the server. However, it’s important to ensure that your code is secure and that users cannot upload or delete files maliciously.