PHP Tutorial Tutorials - PHP File Open

PHP File Open

The PHP fopen() function is used to open a file.
Syntax:

fopen ( string $filename , string $mode ) : resource

The first parameter $filename specifies the name of the file you want to open.
The $mode parameter specifies in which mode the file should be opened.
The return value is a resource handle.

<?php
    $handle = fopen("data.txt", "r");
?>

PHP Open File Mode

The file may be opened in one of the following modes:

mode Description
'r' Open the file in read-only mode
'r+' Open the file in read-write mode
'w' `Truncate the file to zero length.If the file does not exist, attempt to create it.
'w+' Open the file in read-write mode.Truncate the file to zero length.If the file does not exist, attempt to create it.
'a' Open the file in write-only mode.Append content to the end of file.
'a+' Open the file in read-write mode.Append content to the end of file.
'x' Create and open for writing only;If the file already exists, it will fail by returning FALSE.
'x+' Create and open for reading and writing ;If the file already exists, it will fail by returning FALSE.
'c' Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated, nor the call to this function fails.
'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.
'e' Set close-on-exec flag on the opened file descriptor.

We can use file_exists() function to check if the file exists before trying to open it.

<?php
$filename = "data.txt";
 
if(file_exists($filename)){
    $handle = fopen($filename, "r"); // Open in `read-only` mode
} else{
    echo "The file $filename does not exist";
}
?>
Date:2019-10-01 02:53:54 From:www.Lautturi.com author:Lautturi