PHP provides a variety of functions and features for interacting with the file system. Here's a brief overview of the file system operations can be performed in PHP:
The fopen() function is used to open a file in PHP.
<?php
resource fopen ( string $filename , string $mode [,
bool $use_include_path = false [, resource $context ]] )
?>
$filename: Specifies the name of the file or URL to open. It can be a local file or a URL.
$mode: Specifies the mode in which to open the file. This is a string that can contain one or more of the following characters:
Example
<?php
// Specifing the file name
$filename = "file.txt";
// Open the file for reading
$file = fopen($filename, "r");
?>
The $filename is the name of the file we want to open.
We use fopen($filename, "r") to open the file in read mode.
The fclose() function in PHP is used to close an open file.
<?php
bool fclose(resource $handle);
?>
<?php
// Close the file
$closed = fclose($file);
?>
The fread() function is used to read the content of a file in PHP.
<?php
string fread(resource $handle , int $length);
?>
Note: First argument is resource & second argument is file size.
<?php
$filename = "file.txt";
//open file in read mode
$handle = fopen($filename, "r");
//read file
$contents = fread($handle, filesize($filename));
//printing data of file
echo $contents;
//close file
fclose($handle);
?>
The fwrite() function is used to write content of the string into file in PHP.
<?php
fwrite(resource $handle , string $string [, int $length ] );
?>
<?php
//open file in write mode
$fo = fopen('test.txt', 'w');
// write in a open file
fwrite($fo, 'hello ');
fwrite($fo, 'Geeks');
fclose($fo);
?>
The unlink() function is used to delete a file in PHP.
<?php
bool unlink(string $filename [, resource $context ] )
?>
<?php
unlink('test.php');
?>
The copy() function is used to copy a file in PHP.
<?php
copy($sourceFilePath, $destinationFilePath);
?>
<?php
$sourceFile = 'path/sourceFile.php';
$destinationFile = 'path/destinationFile.php';
copy($sourceFile, $destinationFile);
?>
The rename() function is used to rename a file in PHP.
<?
rename($oldFilePath, $newFilePath);
?>
<?php
$oldFilePath = '/oldPath/file.php';
$newFilePath = '/newPath/file.php';
rename($oldFilePath, $newFilePath);
?>
PHP File System allows us to create file, read file line by line, read file character by character, write file, append file, delete file and close file.