SoFunction
Updated on 2025-03-03

PHP implements a method to open a file in a read-only manner

This article describes the method of php to open a file in a read-only manner. Share it for your reference. The specific analysis is as follows:

In php, you can open a file through fopen(). The second parameter is set to "r" to indicate that it has been opened read-only. The function returns a file handle, and other functions can read the file in different ways through this file handle.

<?php 
$file = fopen("/tmp/", "r");
print("Type of file handle: " . gettype($file) . "\n");
print("The first line from the file handle: " . fgets($file));
fclose($file); 
?>

The above code returns the following results

Type of file handle: resource
The first line from the file handle: Welcome to php tutorials

After the file reading is completed, you need to use the fclose() function to close the file handle to free the resource

I hope this article will be helpful to everyone's PHP programming.