MOTOSHARE 🚗🏍️

Rent Bikes & Cars Directly from Owners

Motoshare connects vehicle owners with people who need bikes and cars on rent. Owners earn from idle vehicles, and renters get flexible ride options.

Visit Motoshare

How to Read a Whole file at once in PHP?

php

How to Read a Whole file at once?

file_get_contents( ) Function is used to read entire file into a string. This function is the preferred way to read the contents of a file into a string. Because it will use memory mapping techniques, if this is supported by the server, to enhance performance. This function is binary-safe (meaning that both binary data, like images, and character data can be written with this function). The function returns the read data or FALSE on failure.

What is file_get_contents() Function?

The file_get_contents( ) function in PHP is a built-in function for reading a file and converting it to a string. The function makes advantage of server-supported memory mapping methods, which improves speed and makes it a favored method of reading file data.

Syntax:

file_get_contents($path, $include_path, $context, 
                              $start, $max_length)

Parameters:

The PHP method file_get_contents() takes one necessary parameter and four optional options.

  • $path: It provides the location of the file or directory to be examined.
  • $include_path: It’s an optional parameter that searches the include path (in php.ini) for a file even if it’s set to 1.
  • $context: It is an optional argument for specifying a custom context.
  • $start: It’s an optional argument that specifies where to start reading from in the file.
  • $max_length: It’s an optional parameter that specifies how many bytes should be read.

Return Value:

On success, it returns the read data; on failure, it returns FALSE.

Errors And Exception: 

  • If you wish to open a file that contains special characters like spaces, you must first encode it with urlencode ().
  • The file_get_contents() method produces a non-Boolean result that evaluates to FALSE, but it can also return a Boolean value.
  • If filename cannot be found, maxlength is less than zero, or searching to the given offset in the stream fails, an E WARNING level error is produced.

Let’s take examples to explain how file_get_contents() works:-

Input:  file_get_contents('https://www.scmgalaxy.com/');
Output: A computer science portal for scmgalaxy

Input:  file_get_contents('test.txt', FALSE, NULL, 0, 14);
Output: A computer science portal for scmgalaxy


Example 1:-

Output: 

A computer science portal for scmgalaxy

Example 2:-

Output:-

A computer science portal for scmgalaxy

Ashwani Kumar
Latest posts by Ashwani Kumar (see all)
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x