How To Use PHP file() and readfile() Functions To Read PHP File? – POFTUT

How To Use PHP file() and readfile() Functions To Read PHP File?


PHP programming language provides file() and readfile() functions in order to read a file. In this tutorial, we will learn how to use file() and readfile() functions in order to read text or similar ASCII files like PHP files.

file() Function and Syntax

file() function has a very basic syntax where some of the parameters are optional.

file(PATH,INCLUDE_PATH,CONTEXT)
  • PATH is used to specify the path and file name we want to read
  • INCLUDE_PATH is an optional parameter and if set to 1 the path configuration in the `php.ini` will we set
  • CONTEXT is an optional parameter and specifies the handle of the file if its already opened.

readfile() Function and Syntax

readfile() function uses the same syntax and parameters with the file() function which is like below.

file(PATH,INCLUDE_PATH,CONTEXT)
  • PATH is used to specify the path and file name we want to read
  • INCLUDE_PATH is an optional parameter and if set to 1 the path configuration in the `php.ini` will we set
  • CONTEXT is an optional parameter and specifies the handle of the file if its already opened.

file() Function with PHP File

In this part, we will make an example with the file () function where we will read a file named example.txt like below. Then we will put the read content an array named text. We will print the $text  with the print_r() function.

<?php

$text=file("example.txt");

print_r($text);

?>
file() Function with PHP File
file() Function with PHP File

readfile() Function with PHP File

readfile() function reads the whole file and put into the given variable as a complete string variable. The difference with the read() function is the output is not an array in line by line.

<?php

$text=file("example.txt");

print_r($text);

?>
readfile() Function with PHP File
readfile() Function with PHP File

LEARN MORE  What Is A File?

Leave a Comment