php

Understanding file and directories


PHP FILE:

PHP's file system functions provide a powerful set of tools for working with files and directories on the web server. Whether it's creating, accessing, or manipulating files, PHP enables server-side operations that are essential for various web applications.

 
 

File Handles and Opening Files:

1. File Handles (fopen, fclose):

fopen() // Opens a file or a URL and returns a file pointer resource.
fclose() // Close a file or a URL

fopen

  • Purpose: Opens a file and returns a file handle.
  • Syntax: fopen(filename, mode)
  • Modes:
    • 'r': Read only
    • 'w': Write only, truncates or creates a file
    • 'a': Write only, appends or creates a file
    • 'r+': Read and write
    • 'w+': Read and write, truncates or creates a file
    • 'a+': Read and write, appends or creates a file

fclose

  • Purpose: Closes an open file handle.
  • Syntax: fclose(file_handle)
<?php
$fileHandle = fopen("example.txt", "w"); // Open file for writing
if ($fileHandle) {
    fwrite($fileHandle, "Hello, Codersmile!"); // Write to the file
    fclose($fileHandle); // Close the file
    echo "File written and closed successfully.";
} else {
    echo "Failed to open the file.";
}
?>


Reading from Files:

1. Reading Fixed-Length Data(‘fread’):

fread() // Reads a specified number of bytes from a file.

2. Reading Line by Line(‘fgets’):

Fgets() // Reads a line from a file.

 

3. Reading Entire File at Once:

File_get_contents() // Reads the entire content of a file into a string.

 

Writing to Files:

1. Writing Data to Files():

fwrite() //Writes the contents of a string to a file.

 

2. Appending to Files:

File_puRt_contents() // Writes data to a file. It appends content to the end

 

File Information and Manipulation:

1. Checking File Existence:

file_exits() //Checks whether a file or directory exists.

 

2. File Information:

filesize() // Returns the size of the file.
filetype() // Returns the file type.
filectime() // Returns the creation time of the file.
filemtime() // Returns the last modification time of the file.

 

3. Deleting Files:

unlink() // Deltes a file.