Store data in file php

Store data in file php

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Java classes and object methods

Источник

Write to Files and Read Files With PHP

Monty Shokeen

Monty Shokeen Last updated May 7, 2022

In this tutorial, you’ll learn several important functions in PHP which are sufficient for all your basic file reading and writing needs. You’ll learn how to read a file, write to a file, write to a text file, and check if a file exists.

File handling is something that you will need to do very often as a PHP developer.

You could use PHP file handling functions to manipulate files in different ways. These functions could be used to build features in your applications that range from custom error logging to storing cached files. Examples of utility tools that you could build with these functions are:

  • custom logging and debugging tools
  • application configuration storage
  • front-end and application caching
  • localization support
  • and many more

Luckily, PHP provides a lot of functions to read and write data to files. In this tutorial, I’ll show you the easiest ways to read data from a local or remote file and how to use flags to write to files exactly how we want.

Section Key Functions
Checking if a File Exists file_exists() , is_file()
Reading Data From a File in PHP file_get_contents()
Writing Data to a File in PHP file_put_contents()
Examples of Reading and Writing Data file_get_contents() , file_put_contents()
Reading and Writing to Files With Streams fopen() , fread() , fwrite()

Checking if a File Exists

Your very first step when trying to read data from a file or writing something to it should be to check if the file already exists. Trying to read data from a file which does not exist will result in a warning from PHP and will probably crash your code.

Читайте также:  Php double question mark

The easiest way to check if a file exists is to use the PHP file_exists($filename) function. It will return true if a file or directory with the given $filename exists and false otherwise. This might be obvious, but I would like to point out that $filename doesn’t have to just be the name of a file. It can also be an absolute or relative path. For example, we could use prime_numbers.txt or science/project/periodic_table.txt.

It’s also important to remember that this function will also return false for files which are inaccessible due to safe mode restrictions.

Another function that you can use to check for the existence of a file is is_file() . In contrast to file_exists() , this function will only return true if the specified path points to a file and not a directory.

Making Sure That the File Actually Exists

If the code you are writing performs a lot of file operations on a particular file, you might get incorrect results using the above functions. This is because the results of the execution of both file_exists() and is_file() are cached in order to improve performance. PHP also caches the values returned by other filesystem functions like filesize() , filemtime() , etc.

You can call clearstatcache() to make sure that any information you are accessing for a file is up to date.

This is generally only a problem if the same file is being accessed multiple times in a single script to know its status. Also, the cached data is cleared if you delete the file inside the script using the unlink() function. This basically means that you probably won’t face any caching-related problems, but it is still good to know that you can clear the cache in case the information goes stale or if you are getting unexpected results when trying to access information about a file.

Reading Data From a File in PHP

The file_get_contents() Function

One of the easiest ways to read data from a file in PHP is with the help of the file_get_contents($filename, $use_include_path, $context, $offset, $maxlen) function. It will simply read the entire file and give it to you in the form of a string. All the parameters except the first one are optional.

The second parameter accepts a boolean value to determine if it should look for a file in the location specified by the include path, which can be set using the set_include_path() function.

You can use the third parameter to specify a bunch of options to refine how the files are accessed. You can use it to specify header values like the Cookies and Host , as well as the HTTP method.

The $offset parameter determines the point where reading starts on the original file. Providing a negative value will start counting from the end. The support for negative offsets was only added in PHP 7.1.0. It is worth noting that offset only works with local files and is not supported for remote files.

The file_get_contents() function reads the whole file at once by default. You can change this behavior by providing a value for the $maxlen parameter. The length of characters to be read is counted from the offset value.

The file_get_contents() function reads the whole file at once by default. You can change this behavior by providing a value for the $maxlen parameter. The length of characters to be read is counted from the offset value.

You can use this function to open remote files, but that would be possible only if the value of the allow-url-fopen option in php.ini is true or 1 .

Writing Data to a File in PHP

The file_put_contents Function

One of the easiest ways to write data to a file in PHP is with the help of the file_put_contents($filename, $data, $flags, $context) function.

The $filename parameter determines the file in which the data will be written. The second parameter is the data that you want to write to the file. Most of the time it will be a string, but it could also be an array or a stream resource.

Remember that PHP will automatically create a file with the given name for you if it doesn’t already exist. However, it won’t create any directories for you. This means that you can store a file with the name On the Origin of Species [Charles Darwin].txt without any error. However, setting $filename to Biology/Evolution/On the Origin of Species [Charles Darwin].txt, if Biology/Evolution/ doesn’t already exist, will result in an error.

The $flags parameter determines how the content will be written to a file. It can have any or all of the following three values:

  • FILE_USE_INCLUDE_PATH —This tells PHP to search for the given file name in the include directory.
  • FILE_APPEND —This will tell PHP to append the data you passed to the function to the existing data in the file. It could be useful if you are storing data in a file like a log or a personal diary. Recording new data like temperature or events that happened to you today won’t overwrite something you recorded yesterday.
  • LOCK_EX —This will tell PHP to get a lock on the file before starting to write content into it. It can prevent unexpected things from happening when two different scripts are reading or writing data to the same file. With this particular value, you will get an exclusive lock on the file. You can read more about these locks in the PHP documentation of the flock() function.

This function returns the number of bytes that were written to the file on success and false on failure. However, you must still use the strict equality operator to check if it was successful in writing content to the file. That’s because code that writes 0 bytes to the file will still evaluate to false.

Examples of Reading and Writing Data

In this section, we’ll look at a couple of real-world examples to demonstrate how you can read files.

The file_get_contents Function

You can head over to the Project Gutenberg website and try to download files using the file_get_contents() function. Once you have the data in a string, you can also simply store it in a local file using the file_put_contents() function. The following example will make this clear:

Источник

Оцените статью