PHP File Handling

In PHP, file handling allows you to read from and write to files on the server's file system. PHP provides a set of built-in functions and techniques to perform various file operations, such as opening, reading, writing, and closing files.


Here are some common file handling functions in PHP:


1. Opening a File:

- `fopen()`: Opens a file and returns a file pointer for subsequent file operations.


2. Reading from a File:

- `fgets()`: Reads a line from the file pointer.
- `fgetc()`: Reads a single character from the file pointer.
- `file()`: Reads an entire file into an array, with each element representing a line.


3. Writing to a File:

- `fwrite()`: Writes data to the file.
- `file_put_contents()`: Writes data to a file in a single function call.


4. Closing a File:

- `fclose()`: Closes an open file pointer.


Here's an example of reading from a file and writing to a file:

php
// Reading from a file
$filename = 'example.txt';
$file = fopen($filename, 'r') or die('Unable to open file.');

while (!feof($file)) {
    echo fgets($file); // Read a line from the file and print it
}

fclose($file); // Close the file pointer

// Writing to a file
$outputFilename = 'output.txt';
$outputData = 'This is some data that we want to write to the file.';

$outputFile = fopen($outputFilename, 'w') or die('Unable to open file.');

fwrite($outputFile, $outputData);

fclose($outputFile); // Close the file pointer

In this example, the `fopen()` function is used to open the file for reading (`'r'`) and writing (`'w'`). The `fgets()` function is used to read each line from the input file, and the `fwrite()` function is used to write data to the output file.


It's important to handle file operations carefully, especially when dealing with user input, to prevent security issues such as directory traversal or arbitrary code execution. Always validate and sanitize user input before using it in file operations. Additionally, ensure that the file permissions are properly set to restrict unauthorized access to the files.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext