File handling functions file_get_contents(), file_put_contents()

File handling functions file_get_contents(), file_put_contents()

In addition to the fopen(), fread(), fwrite(), and fclose() functions, several other basic, high-level file handling functions are also available to the user, including the file_get_contents() and file_put_contents() functions. These functions help PHP programming read existing files and create content and information in files without manually managing file pointers.

File handling functions file_get_contents(), file_put_contents()

So, let’s take a closer look at other file handling functions in PHP programming.

The file_get_contents() function in PHP.

In PHP file handling, the file_get_contents() function helps read the complete data and information of an existing file in a string format. The file_get_contents() function is useful in special orders when a programmer wants to read a small file from a file, or when a programmer does not need to process a file in small pieces.

Syntax of the file_get_contents() function.

$content = file_get_contents($filename, $use_include_path, $context, $offset, $maxlen);

file_get_contents() function explanation.

  • $filename – This is the path to the file the user wants to read in file handling.
  • $use_include_path (optional) – This is whether to search the include path for the current file. The default is false.
  • $context (optional) – This is a reference resource for a file. This is a method to indicate additional optionality for file access. Its default value is zero.
  • $offset (optional) – This is the starting position from which to start reading the file in file handling. Its default value is 0.
  • $maxlen (optional) – This is the maximum file length number of bytes to read the file in file handling. Its default value is the entire file.

Example of reading a file with the PHP file_get_contents() function.

<?php

$filename = “test.txt”;

$content = file_get_contents($filename);

if ($content !== false) {

echo “File Content is – ” . $content;

} else {

echo “Unable to read the file content”;

}

?>

In this example, file_get_contents() reads the complete content information of the test.txt file and stores it in the $content program variable. If the file read operation is successful, it displays the current file’s content information as output. If the given file cannot be read, it returns a false value in the output format.

Example with file_get_contents() and URL.

In PHP file handling, programmers can also apply file_get_contents() to retrieve the contents of a particular URL, such as an API endpoint or a webpage.

<?php

$url = “https://www.vcanhelpsu.com”;

$content = file_get_contents($url);

if ($content !== false) {

echo “open webPage Content – ” . $content;

} else {

echo “unable to fetch the above URL”;

}

?>

file_put_contents() in PHP.

In PHP file handling, file_put_contents() is used to create data and information in a file. If the file does not already exist in storage, this function will first create it. If the file already exists, it can overwrite the file or append content to it, depending on flags indicated by the user.

Syntax of file_put_contents().

file_put_contents($filename, $data, $flags, $context);

file_put_contents() function explanation.

  • $filename – This is the path to the file where the file data will be created.
  • $data – This is the file data the user wants to create in the file.
  • $flags (optional) – You can use flags to modify file behavior. For example,
  • FILE_APPEND – This appends data and information to the existing file instead of overwriting it.
  • LOCK_EX – This acquires an exclusive lock when writing to the file.
  • $context (optional) – This is a reference resource for additional options. Its default value is zero.

Example of writing to a file with file_put_contents().

<?php

$filename = “test.txt”;

$data = “here we add some new content to the file”;

$result = file_put_contents($filename, $data);

if ($result !== false) {

echo “file data written process success”;

} else {

echo “file data written failed”;

}

?>

In this example.

Here file_put_contents() creates or writes the string $data to test.txt. If the file doesn’t already exist, it will create that file first. If the file already exists, it will overwrite the previous file contents.

File example with the FILE_APPEND flag appending data.

In PHP file handling, if users want to add new digital content and information to an existing file instead of overwriting it, they can use the FILE_APPEND function flag.

<?php

$filename = “test.txt”;

$data = “\n let add append some additional data to the file”;

$result = file_put_contents($filename, $data, FILE_APPEND);

if ($result !== false) {

echo “Data appended operation successful”;

} else {

echo “Data append operation failed”;

}

?>

Here, instead of overwriting the existing file content information, it will append the new data to the end of the file.

Error Handling in PHP.

If an error occurs while processing a file, both the file_get_contents() and file_put_contents() functions return false. Therefore, testing the return value is important for proper file handling error management.

Example of error handling with the PHP file_get_contents() function.

<?php

$filename = “notexist_file.txt”;

$content = file_get_contents($filename);

if ($content === false) {

echo “Display Error reading the file, please verify file must exist and be readable.”;

}

?>

Example of error handling with file_put_contents() in PHP.

<?php

$filename = “test_file.txt”; // let’s predict this file is not writable

$data = “let’s add some fresh content to the file”;

$output = file_put_contents($filename, $data);

if ($output === false) {

echo “It displays an error writing into the file. Please verify that the file is writable or not.”;

}

?>

file_get_contents() and file_put_contents() performance considerations in PHP.

file_get_contents() and file_put_contents() are very useful file handling functions in PHP file handling programming, but they may be inefficient or incompatible with large file sizes because these functions may read or write the entire file at once. If users are working with large file sizes that contain several gigabytes, using the fopen(), fread(), and fwrite() functions is often a better option for detailed control over the read and write processes in such files.

Practical use cases for file_get_contents() and file_put_contents() in PHP.

Reading a configuration file in PHP.

$config = file_get_contents(“config.json”);

$config_data = json_decode($config, true);

// Apply $config_data to application settings.

Logging data to a file in PHP.

$log_data = “Log entry: ” . date(“Y-m-d H:i:s”) . ” – User logged in.”;

file_put_contents(“logfile.txt”, $log_data . PHP_EOL, FILE_APPEND);

Writing JSON data to a file in PHP.

$filedata = [“empname” => “Harry”, “email” => “harry@domain.com”];

file_put_contents(“filedata.json”, json_encode($filedata));

In PHP file handling programming, file_get_contents() and file_put_contents() simplify file management for both small files and general use, making them easier and more compatible than low-level file handling functions (fopen(), fread(), fwrite(), fclose()).

explanation of file_get_contents() and file_put_contents() in the file handling.

File handling FunctionFile handling Function Description
file_get_contents() functionThis function used to Reads the entire content of a file into a string format.
file_put_contents() functionThis function used to Writes data into a file, generally it appending or locking the file for put content.

A Summary of PHP File Handling Functions.

  • Use the file_get_contents() function to read small-level files immediately in file handling programming.
  • Use the file_put_contents() function to write file data in a detailed order in file handling programming.
  • Be alert to possible performance issues with large files in file handling programming. Use the fopen() and fread() functions for better control in such situations.
  • Always check for errors when using these functions in file handling programming.

Leave a Reply