fread(): Reading Data from a File


**fread(): Reading Data from a File**

The `fread()` function in PHP is used to read data from a file. It is a versatile function that allows you to specify the number of bytes to read, the offset from which to start reading, and the file handle of the file to read from.

**Syntax**

“`php
fread(resource $handle, int $length [, int $offset = 0]): string
“`

**Parameters**

* `$handle`: The file handle of the file to read from. This handle must have been previously opened using the `fopen()` or `file()` function.
* `$length`: The number of bytes to read from the file.
* `$offset` (optional): The offset from which to start reading. This parameter is optional and defaults to 0, which means that reading will start from the beginning of the file.

**Return Value**

The `fread()` function returns a string containing the data that was read from the file. If an error occurs, `fread()` will return `FALSE`.

**Example**

The following example reads the first 10 bytes from the file “test.txt”:

“`php
$handle = fopen(“test.txt”, “r”);
$data = fread($handle, 10);
fclose($handle);

echo $data;
“`

Output:

“`
Hello, worl
“`

**fread() vs. fgets()**

The `fread()` and `fgets()` functions are both used to read data from a file, but they have different purposes. The `fread()` function reads a specified number of bytes from a file, regardless of line breaks. The `fgets()` function reads a single line from a file, up to a maximum of 4096 bytes.

**When to Use fread()**

The `fread()` function is useful when you need to read a specific number of bytes from a file, or when you need to read data from a file without being concerned about line breaks. For example, you might use `fread()` to read the contents of a binary file.

**fread() Tips**

* You can use the `fseek()` function to change the current position of the file pointer. This can be useful for skipping over unwanted data or for reading data from a specific location in the file.
* The `fread()` function can be used to read data from a pipe or other stream, not just from a file.
* The `fread()` function can be used to read data from a URL using the `fopen()` function with the `r` mode.