The fread() function is used to read from a file. It allows you to read from any stream or file, as long as it’s a binary stream. fread() reads the specified number of bytes into the given array, starting at the position in bytes. Let’s take a look at how the PHP fread() function works and see some examples of how to use it. Continue reading to learn more.

Advertisement

How to use PHP fread() function?

The fread() function is used to read from a file. It allows you to read from any stream or file, as long as it’s a binary stream. fread() reads the specified number of bytes into the given array, starting at the position in bytes. The syntax of the fread() function is –

The fread() function parameters are:

  • file_handle: This parameter specifies the file from which the bytes will be read. The value can be either a file path on a local disk or a remote file.
  • length: This parameter specifies the number of bytes to read. The must be a positive integer (non-zero)

PHP fread() example: Read a specific amount of bytes

If you want to read a specific amount of bytes from a file, you can provide the starting position of the bytes to read and the number of bytes to read. You can provide the length parameter to read a specific number of bytes from the file. In this example, we are reading 20 bytes from the beginning of the file. Since we are reading 20 bytes from the beginning of the file, the first 20 characters in the file are read.

PHP fread() example: Read all bytes at once

If you want to read all the bytes in a file, the length parameter needs to calculate first as the size of the file. The length can be calculated with the filesize() function. In this example, we are reading all the bytes in a file at once. This example will display all the bytes in the file in the console. Since we are reading all the bytes in the file at once, the file is completely read, and the entire file is displayed in the console.

PHP fread() example: Read from remote file

The PHP fread() function also allows reading content from a remote path. You can simply specify the remote file URL as the filename. Then use fopen() to open the file in read mode. For example:

Conclusion

This tutorial helped you to learn about the PHP fread() function. Using this file we can read the content of a binary file available on a local disk or remote server.

Share.
Leave A Reply

Exit mobile version