We have given a file stored on XAMPP server and the task is to read the file from server and display the file content on the screen using PHP. We use some PHP functions to solve this problem.
File: A file is set of data stored in a disk in different formats. For example – .txt, .exe, .pdf etc
fopen() function: The fopen() function in PHP is an inbuilt function which is used to open a file or a URL. It is used to bind a resource to a steam using a specific filename. The filename and mode to be checked are sent as parameters to the fopen() function and it returns a file pointer resource if a match is found and a False on failure. The error output can be hidden by adding an ‘@’ in front of the function name.
Syntax:
fopen('filename', filemode)
Here, file name is name of the file and file mode includes read(r) mode,
write(w) and binary(b) mode etc.
- fopen($geek, r) — Here we are opening geek file in read mode.
- fopen($geek, r+) — Here we are opening geek file in read and write mode.
- fopen($geek, w) — Here we are opening geek file in write mode.
- fopen($geek, w+) — Here we are opening geek file in read and write mode.
- fopen($geek, b) — Here we are opening geek file in read and write mode.
Requirements:
XAMPP web server — If you have not installed XAMPP/WAMP web server then please install it by using the following steps:
Link to install: https://www.apachefriends.org/download.html
Start the XAMPP Server
Open the notepad and type the below code:
PHP
<?php // File to be read $file = "./welcome.txt" ; // Opening file $f = fopen ( $file , "r" ) or exit ( "Unable to open file!" ); // Read file line by line until // the end of file (feof) while (! feof ( $f )) { echo fgets ( $f ). "<br />" ; } // Closing file fclose( $f ); ?> |
Data in welcome.txt file are:
GEEKS FOR GEEKS IS BEST FOR COMPUTER SCIENCE
Place these two files in folder (Path is show here)
Running the Script Type the following URL in the browser: localhost/gfg/1.php
Output: