HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP File Handling

File handling is an important part of any web application. You often need to open and process a file for different tasks.




PHP Manipulating Files

PHP has several functions for creating, reading, uploading, and editing files.



• PHP readfile() Function

The readfile() function reads a file and writes it to the output buffer.


Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:

AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language


The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the number of bytes read on success):


Example


<!DOCTYPE html>
<html>
<body>

<?php
echo readfile("webdictionary.txt");
?>

</body>
</html>

Output

AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language236



If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error:


The readfile() function is useful if all you want to do is open up a file and read its contents.