EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP File Handling

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP File Handling

PHP File Handling

Overview of PHP File Handling

All modern software requires to interact with files. They either require to accept inputs in the form of files or either generate output and add it to the file. In either scenario, the capability of integrating with files has become an integral feature of almost all software that is used to run businesses. For any application, the handling of files is necessary. The file must be processed for some tasks to be performed. File handling in PHP is similar to file handling by any language such as C. PHP has a lot of normal file functions to work with.

Use Case for PHP File Handling Capacity

As an example, banks would require software that would help them generate reports like bank account statements for 3 months or 6 months period, e-commerce companies would require to print reports related to stock inventory and sales and last but not the least applications related to stock market trade would require daily stock prices to be provided in the form of readable file. I am sure with this example, You would agree that any software that supports a business function would require you to read or write data to a file.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Since file handling capacity is almost a necessity in the modern-day application, all prominent programming languages like Python, Java, C#, and PHP provide inbuilt file handling functions that are utilized by developers to develop interactive applications.

File Handling Capability in PHP

PHP supports the following file formats for reading and write operations.

  • Text Files: Files with extension .txt
  • Log Files: Files with extension .log
  • Custom Extensions: Files with a custom extension like .abc
  • CSV Files: Files with extension .csv
  • Image Files: Files with extension .jpg/png/gif
  • File with Initialization Setting: Files with extension .ini

File Handling Functions in PHP

PHP provides a wide range of in-built functions to perform various file operations. These file functions work well with all OS systems like Linus, Unix, MAC, and Windows. However, file names in MAC OS and Windows are not case sensitive while those in Unix and Linux are case sensitive. Hence to avoid any confusion or errors, it is considered a best practice to names all files in lower cases as it ensures complete platform compatibility.

Now that we have a high-level understanding of how php file handling functions work, let’s understand these functions one by one.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

1. file_exists() Function

The function is used to verify the existence of the filename supplied to it as its parameter. It is used to avoid errors that could be caused by attempting to read or write a non-existent file.

Syntax:

<?php
file_exists($file_name) //where file_name  would be a file with one of the supported extensions
?>

The file_exists() would return a True value if the file exists else would return false if the file does not exist.

Now let’s use this function in a code spec to check the existence of a file. Let’s place a file by the name “mysettings.ini” in the root folder and try to access it with the following code.

Code:

<?php
if (file_exists('mysettings.ini))
{
echo 'yay! file found!';
}
else
{
echo 'Sorry! mysettings.ini does not exist';
}
?>

Output:

PHP File Handling 1-1

Now, if we delete the file from that location and run the above code, we would see the following output.

PHP File Handling 1-2

2. fopen() Function

The fopen function is used in php to open files which are to be read by the application.

Syntax:

<?php
fopen($fname,$mode,$use_include_path,$context);
?>

In the above syntax, $fname stands for the file name, $mode stands for the mode in which we’d like to open the file. $mode can be either of the following values.

  • r: For opening the file in only read-only mode. It returns false if the file name supplied is not found on the location supplied.
  • r+: For opening the file in both read and write mode. Similar to ‘r’, it also returns false if a file is not found.
  • w: For opening the file in only write-only mode. If the file supplied doesn’t exist, it attempts to create one.
  • w+: For opening the file in both read and write mode. Similar to ‘w’, it also attempts to create a file if the file name supplied is not found.
  • a: For opening the file in write-only mode and appending to the end of the file. If the file supplied doesn’t exist, it attempts to create one.
  • a+: For opening the file in both read and write mode. Similar to ‘a’, it also attempts to create a file if the file name supplied is not found.

3. fwrite() Function

As the name suggests, this function is used to write content to files.

Syntax:

<?php
fwrite($handle, $data_string, $len);
?>

Where $handle is the file location, $data_string is the text string we would like to write to the file and $len is the optional parameter to specify the maximum length of the file.

4. fclose() Function

The fclose() function is used in php when the read/write operations on file are completed and we would like to close the file.

Syntax:

<?php
fclose($file_handle);
?>

Where $file_handle stands for the file pointer.

5. fgets() Function

The fgets() function is used in php to read the file line by line.

Syntax:

<?php
fgets($file_handle);
?>

Where $file_handle stands for the file pointer.

6. copy() Function

The copy() function allows us to copy a file in php.

Syntax:

<?php
copy($file1, $file2);
?>

Where $file1 is the original file and $file2 is the copied file location.

7. unlink() Function

The unlink() function in Php is used to delete a file.

Syntax:

<?php
unlink($filename);
?>

Where the $filename is the filename to be deleted.

Conclusion

With the above example, we can easily conclude that php has a wide variety of in-built functions that simplify reading and writing operations on the file. The most commonly used function include fopen() to open the file in different modes, fwrite() to write data to the file, fread() to read the file content, fclose() to close the file once the necessary operation is done, copy() to copy one file content to another and unlink to delete the unwanted files.

Recommended Articles

This is a guide to PHP File Handling. Here we discuss the overview, use case for PHP file handling capacity along with the top 7 file handling functions. You may also look at the following articles to learn more –

  1. File Handling in Java
  2. File Handling in C#
  3. File Handling in C
  4. File Handling in C++

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you