Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is fread in PHP?

Sheza Munir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

PHP offers many functions for file manipulation. The fread function in PHP reads the content from an already open file. It is a binary-safe read option that allows binary data in addition to normal text content to be read.

Syntax

The syntax for fread function is shown below:

fread(resource $stream, int $length): string|false

Parameters

The fread function has two parameters:

  • file: This is a required parameter. This is the pointer of the file stream that points to a file that is already open. The fread function stops reading from the file at the end of the file or when it reaches the specified lengthnumber of bytes, whichever comes first.
  • length: This is also a required parameter. This parameter specifies the number of bytes to be read from the file.

Return value

The fread() function returns the read content from the file in the form of a string.

If it is unable to return the content due to an error or by coming to the end of the file, it returns false.

Code

The following code shows how we can use the fread function.

main.php
test.txt
<?php
$file = fopen("test.txt","r"); // open the file
while(!feof($file)) //checks if at end of the file
{
echo fread($file, 32); //reads the content of 32 bytes from the file
}
fclose($file); // close the file
?>

RELATED TAGS

php

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring