How To Open a File for Reading


How To Open a File for Reading? - PHP Script Tips - Reading and Writing Files



If you want to open a file and read its contents piece by piece, you can use the fopen($fileName, "r") function. It opens the specified file, and returns a file handle. The second argument "r" tells PHP to open the file for reading. Once the file is open, you can use other functions to read data from the file through this file handle. Here is a PHP script example on how to use fopen() for reading:

$file = fopen("/windows/system32/drivers/etc/hosts", "r");
print("Type of file handle: " . gettype($file) . "\n");
print("The first line from the file handle: " . fgets($file));

This script will print:

Type of file handle: resource
The first line from the file handle: # Copyright (c) 1993-1999

Note that you should always call fclose() to close the opened file when you are done with the file.

2007-04-22, 4632👍, 0💬