In this section, we will explore various PHP functions that allow you to handle files effectively. File handling is a crucial aspect of web development, enabling you to read, write, and manipulate files on the server. We will cover the following key functions:

  1. fopen()
  2. fclose()
  3. fread()
  4. fwrite()
  5. fgets()
  6. file_get_contents()
  7. file_put_contents()
  8. fseek()
  9. feof()
  10. unlink()

  1. fopen()

The fopen() function is used to open a file. It returns a file handle resource on success or false on failure.

Syntax:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

Modes:

  • 'r' - Read only. Starts at the beginning of the file.
  • 'r+' - Read/Write. Starts at the beginning of the file.
  • 'w' - Write only. Opens and truncates the file; or creates a new file if it doesn't exist.
  • 'w+' - Read/Write. Opens and truncates the file; or creates a new file if it doesn't exist.
  • 'a' - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist.
  • 'a+' - Read/Write. Preserves file content by writing to the end of the file.
  • 'x' - Write only. Creates a new file. Returns false if the file already exists.
  • 'x+' - Read/Write. Creates a new file. Returns false if the file already exists.

Example:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    echo "File opened successfully.";
    fclose($file);
} else {
    echo "Failed to open the file.";
}
?>

  1. fclose()

The fclose() function is used to close an open file pointer.

Syntax:

bool fclose ( resource $handle )

Example:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    // Perform file operations
    fclose($file);
}
?>

  1. fread()

The fread() function reads up to length bytes from the file pointer referenced by handle.

Syntax:

string fread ( resource $handle , int $length )

Example:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    $content = fread($file, filesize("example.txt"));
    echo $content;
    fclose($file);
}
?>

  1. fwrite()

The fwrite() function writes the contents of string to the file stream pointed to by handle.

Syntax:

int fwrite ( resource $handle , string $string [, int $length ] )

Example:

<?php
$file = fopen("example.txt", "w");
if ($file) {
    fwrite($file, "Hello, World!");
    fclose($file);
}
?>

  1. fgets()

The fgets() function gets a line from the file pointer.

Syntax:

string fgets ( resource $handle [, int $length ] )

Example:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line;
    }
    fclose($file);
}
?>

  1. file_get_contents()

The file_get_contents() function reads the entire file into a string.

Syntax:

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

Example:

<?php
$content = file_get_contents("example.txt");
echo $content;
?>

  1. file_put_contents()

The file_put_contents() function writes a string to a file.

Syntax:

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

Example:

<?php
file_put_contents("example.txt", "Hello, World!");
?>

  1. fseek()

The fseek() function seeks to a specific position in a file.

Syntax:

int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )

Example:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    fseek($file, 10);
    echo fgets($file);
    fclose($file);
}
?>

  1. feof()

The feof() function checks if the end of the file has been reached.

Syntax:

bool feof ( resource $handle )

Example:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    while (!feof($file)) {
        echo fgets($file);
    }
    fclose($file);
}
?>

  1. unlink()

The unlink() function deletes a file.

Syntax:

bool unlink ( string $filename [, resource $context ] )

Example:

<?php
if (unlink("example.txt")) {
    echo "File deleted successfully.";
} else {
    echo "Failed to delete the file.";
}
?>

Practical Exercise

Task:

  1. Create a PHP script that writes the string "PHP File Handling" to a file named file_handling.txt.
  2. Read the content of the file and display it on the screen.
  3. Append the string " - Practical Exercise" to the file.
  4. Read the updated content of the file and display it on the screen.
  5. Delete the file.

Solution:

<?php
// Step 1: Write to the file
file_put_contents("file_handling.txt", "PHP File Handling");

// Step 2: Read and display the content
$content = file_get_contents("file_handling.txt");
echo "Initial Content: " . $content . "\n";

// Step 3: Append to the file
file_put_contents("file_handling.txt", " - Practical Exercise", FILE_APPEND);

// Step 4: Read and display the updated content
$updatedContent = file_get_contents("file_handling.txt");
echo "Updated Content: " . $updatedContent . "\n";

// Step 5: Delete the file
if (unlink("file_handling.txt")) {
    echo "File deleted successfully.";
} else {
    echo "Failed to delete the file.";
}
?>

Conclusion

In this section, we covered various PHP file handling functions, including how to open, read, write, and delete files. These functions are essential for managing files on the server and are widely used in web development. By practicing the provided exercise, you should now have a solid understanding of how to handle files in PHP. In the next section, we will explore file permissions and how to manage them effectively.

PHP Programming Course

Module 1: Introduction to PHP

Module 2: Control Structures

Module 3: Functions

Module 4: Arrays

Module 5: Working with Forms

Module 6: Working with Files

Module 7: Object-Oriented Programming (OOP)

Module 8: Working with Databases

Module 9: Advanced PHP Techniques

Module 10: PHP Frameworks and Best Practices

Module 11: Project: Building a Web Application

© Copyright 2024. All rights reserved