Skip to content

PHP fgets() Function: Read file line by line

Read file Line by Line using PHP. PHP fgets() function is used for reading single line from file This function takes two arguments

Category
PHP
Versions & support
About PHP →
On this page

PHP fgets() function is used for reading a single line from a file. This function takes two arguments as described below.

1. File specifies the filename to read content
2. Length Optional parameter specifies the number of bytes to read from the file.

Syntax

PHP fgets() function uses the following syntax.

  fgets(file, length)

Example – Read a single line

Below are two examples of a reading single line from a file. Use this example to read the complete first-line content from a file.

Instead of a line, you can also define the number of bytes to read from a file:

Example – Read All Lines

Use this example to read all lines from files one by one using for loop. Use PHP feof() function to find the end of the file.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top