
- PHP - Home
- PHP - Roadmap
- PHP - Introduction
- PHP - Installation
- PHP - History
- PHP - Features
- PHP - Syntax
- PHP - Hello World
- PHP - Comments
- PHP - Variables
- PHP - Echo/Print
- PHP - var_dump
- PHP - $ and $$ Variables
- PHP - Constants
- PHP - Magic Constants
- PHP - Data Types
- PHP - Type Casting
- PHP - Type Juggling
- PHP - Strings
- PHP - Boolean
- PHP - Integers
- PHP - Files & I/O
- PHP - Maths Functions
- PHP - Heredoc & Nowdoc
- PHP - Compound Types
- PHP - File Include
- PHP - Date & Time
- PHP - Scalar Type Declarations
- PHP - Return Type Declarations
- PHP - Operators
- PHP - Arithmetic Operators
- PHP - Comparison Operators
- PHP - Logical Operators
- PHP - Assignment Operators
- PHP - String Operators
- PHP - Array Operators
- PHP - Conditional Operators
- PHP - Spread Operator
- PHP - Null Coalescing Operator
- PHP - Spaceship Operator
- PHP Control Statements
- PHP - Decision Making
- PHP - If…Else Statement
- PHP - Switch Statement
- PHP - Loop Types
- PHP - For Loop
- PHP - Foreach Loop
- PHP - While Loop
- PHP - Do…While Loop
- PHP - Break Statement
- PHP - Continue Statement
- PHP Arrays
- PHP - Arrays
- PHP - Indexed Array
- PHP - Associative Array
- PHP - Multidimensional Array
- PHP - Array Functions
- PHP - Constant Arrays
- PHP Functions
- PHP - Functions
- PHP - Function Parameters
- PHP - Call by value
- PHP - Call by Reference
- PHP - Default Arguments
- PHP - Named Arguments
- PHP - Variable Arguments
- PHP - Returning Values
- PHP - Passing Functions
- PHP - Recursive Functions
- PHP - Type Hints
- PHP - Variable Scope
- PHP - Strict Typing
- PHP - Anonymous Functions
- PHP - Arrow Functions
- PHP - Variable Functions
- PHP - Local Variables
- PHP - Global Variables
- PHP Superglobals
- PHP - Superglobals
- PHP - $GLOBALS
- PHP - $_SERVER
- PHP - $_REQUEST
- PHP - $_POST
- PHP - $_GET
- PHP - $_FILES
- PHP - $_ENV
- PHP - $_COOKIE
- PHP - $_SESSION
- PHP File Handling
- PHP - File Handling
- PHP - Open File
- PHP - Read File
- PHP - Write File
- PHP - File Existence
- PHP - Download File
- PHP - Copy File
- PHP - Append File
- PHP - Delete File
- PHP - Handle CSV File
- PHP - File Permissions
- PHP - Create Directory
- PHP - Listing Files
- Object Oriented PHP
- PHP - Object Oriented Programming
- PHP - Classes and Objects
- PHP - Constructor and Destructor
- PHP - Access Modifiers
- PHP - Inheritance
- PHP - Class Constants
- PHP - Abstract Classes
- PHP - Interfaces
- PHP - Traits
- PHP - Static Methods
- PHP - Static Properties
- PHP - Namespaces
- PHP - Object Iteration
- PHP - Encapsulation
- PHP - Final Keyword
- PHP - Overloading
- PHP - Cloning Objects
- PHP - Anonymous Classes
- PHP Web Development
- PHP - Web Concepts
- PHP - Form Handling
- PHP - Form Validation
- PHP - Form Email/URL
- PHP - Complete Form
- PHP - File Inclusion
- PHP - GET & POST
- PHP - File Uploading
- PHP - Cookies
- PHP - Sessions
- PHP - Session Options
- PHP - Sending Emails
- PHP - Sanitize Input
- PHP - Post-Redirect-Get (PRG)
- PHP - Flash Messages
- PHP AJAX
- PHP - AJAX Introduction
- PHP - AJAX Search
- PHP - AJAX XML Parser
- PHP - AJAX Auto Complete Search
- PHP - AJAX RSS Feed Example
- PHP XML
- PHP - XML Introduction
- PHP - Simple XML Parser
- PHP - SAX Parser Example
- PHP - DOM Parser Example
- PHP Login Example
- PHP - Login Example
- PHP - Facebook Login
- PHP - Paypal Integration
- PHP - MySQL Login
- PHP Advanced
- PHP - MySQL
- PHP.INI File Configuration
- PHP - Array Destructuring
- PHP - Coding Standard
- PHP - Regular Expression
- PHP - Error Handling
- PHP - Try…Catch
- PHP - Bugs Debugging
- PHP - For C Developers
- PHP - For PERL Developers
- PHP - Frameworks
- PHP - Core PHP vs Frame Works
- PHP - Design Patterns
- PHP - Filters
- PHP - JSON
- PHP - Exceptions
- PHP - Special Types
- PHP - Hashing
- PHP - Encryption
- PHP - is_null() Function
- PHP - System Calls
- PHP - HTTP Authentication
- PHP - Swapping Variables
- PHP - Closure::call()
- PHP - Filtered unserialize()
- PHP - IntlChar
- PHP - CSPRNG
- PHP - Expectations
- PHP - Use Statement
- PHP - Integer Division
- PHP - Deprecated Features
- PHP - Removed Extensions & SAPIs
- PHP - PEAR
- PHP - CSRF
- PHP - FastCGI Process
- PHP - PDO Extension
- PHP - Built-In Functions
PHP Filesystem file_get_contents() Function
The PHP Filesystem file_get_contents() function is used to read a file into a string. This function is the preferred to read the contents of a file into a string because it can use memory mapping techniques if this is supported by the server to enhance performance.
This function is similar to file() function except that file_get_contents() function returns the file in a string starting at specified offset up to maxlen bytes.
Syntax
Below is the syntax of the PHP Filesystem file_get_contents() function −
string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )
Parameters
Here are the required and optional parameters of the file_get_contents function −
Sr.No | Parameter & Description |
---|---|
1 |
filename(Required) The name of the file you want to read. |
2 |
use_include_path(optional) This is a boolean value. If set to true, it will search for the file in the include path. |
3 |
context(optional) This parameter allows to specify options like timeout, headers. |
4 |
offset(optional) The starting point from where you want to read the file. |
5 |
maxlen(optional) The maximum number of bytes to read. |
Return Value
It returns the file content as a string. If failed, it returns FALSE.
PHP Version
The file_get_contents() function is introduced as part of core PHP 4.3.0 and work well with the PHP 5, PHP 7, PHP 8.
Example
In this example we will use the PHP Filesystem file_get_contents() function to read a file and print the content of that file. So this is very basic usage of this function.
<?php // Path to the file $file = file_get_contents("/PhpProject/sample.txt", true); echo $file; ?>
Output
This will produce the following result −
tutorialspoint tutorix
Example
This php code will show you how you can use optional parameters of file_get_contents() function and make the changes in the output content.
- In this we have used all the optional parameters.
- The first parameter is the file path.
- The second and third parameters, which are NULL, are optional and not used in this example.
- The fourth parameter - 4, is the starting point in the file. It will start reading from the 4th character.
- The fifth parameter - 10, is the length of the content to read. It will read 10 characters.
<?php // Define the file path here with optional parameters $section = file_get_contents("/PhpProject/sample.txt", NULL, NULL, 4, 10); var_dump($section); ?>
Output
This will generate the below result −
string(10) "rialspoint"
Example
In this PHP code we will see how we can handle the file error for example if the given file is not present in the directory. So if the file is not exist then we can show the error message to the user.
<?php // Assign path of the file $file_path = "/Applications/XAMPP/xamppfiles/htdocs/mac/non_existent.txt"; // Use file_get_contents() function to get the content $content = file_get_contents($file_path); // Check file exists or not if ($content === FALSE) { echo "Error: Unable to read the file at $file_path"; } else { var_dump($content); } ?>
Output
This will create the below outcome −
Error: Unable to read the file at /Applications/XAMPP/xamppfiles/htdocs/mac/non_existent.txt
Example
In this example, our goal is to use a given URL (Uniform Resource Locator) as a file and get the content of that and echo it.
<?php // Reading a file from a URL $url = "https://www.example.com/sample.txt"; // Get the content from the URL $content = file_get_contents($url); // Check the error if ($content === FALSE) { echo "Error: Unable to read the file from the URL"; } else { var_dump($content); } ?>
Output
This will lead to the following outcome −
string(102) "This is a sample url to check that it works!"
Note
It is necessary to handle failures properly, particularly if working with files that might not be accessible or exist.
Summary
To read a file's contents into a string we can use PHP's file_get_contents() function. It has the ability to read the entire file or only specific sections of it. The function works well for basic file reading work, but for efficient operations, proper error handling needs to be implemented.