How to Read a File Starting From a Specific Place Php

Read Fourth dimension: ix mins Languages:

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

Luckily, PHP provides a lot of functions to read and write data to files. In this tutorial, I'll testify 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 desire.

Checking if a File Exists

Your very first stride when trying to read data from a file or writing something to it should be to cheque 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.

The easiest style to check if a file exists is to use the PHP file_exists($filename) function. Information technology will render true if a file or directory with the given $filename exists and simulated otherwise. This might be obvious, but I would like to indicate out that$filename doesn't take to just exist the name of a file. Information technology can besides be an accented or relative path. For instance, we could useprime_numbers.txt or scientific discipline/projection/periodic_table.txt.

It's also of import to remember that this function volition also return faux for files which are inaccessible due to rubber fashion restrictions.

Some other function that y'all can employ to check for the existence of a file is is_file(). In contrast to file_exists(), this office will just return true if the specified path points to a file and not a directory.

Making Certain That the File Actually Exists

If the code you are writing performs a lot of file operations on a detail 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 better functioning. PHP also caches the values returned by other filesystem functions like filesize(), filemtime(), etc.

You can call clearstatcache() to brand sure that any data y'all are accessing for a file is up to appointment.

This is generally only a problem if the same file is being accessed multiple times in a unmarried script to know its condition. Also, the buried data is cleared if yous delete the file inside the script using the unlink() function. This basically means that you probably won't face any caching related problems, only information technology is still good to know that you lot can clear the cache in example the information goes stale or if you lot are getting unexpected results when trying to access information near a file.

Reading Data From a File in PHP

One of the easiest means to read data from a file in PHP is with the help of the file_get_contents($filename, $use_include_path, $context, $commencement, $maxlen) function. Information technology will simply read the unabridged file and give information technology to y'all in the course of a string. All the parameters except the outset one are optional.

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

Yous can utilise the third parameter to specify a agglomeration of options to refine how the files are accessed. You can use it to specify header values similar the Cookies and Host as well equally the HTTP method.

The $first parameter determines the point where reading starts on the original file. Providing a negative value volition first counting from the finish. The support for negative offsets was only added in PHP seven.i.0. Information technology is worth noting that offset only works with local files and is non supported for remote files.

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

This function will render false if it failed to read data from the file you specified. However, information technology tin also render values which evaluate to false, then make certain that you cheque if it really returned imitation using the === operator.

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

Writing Data to a File in PHP

Ane of the easiest ways to write data to a file in PHP is with the help of thefile_put_contents($filename, $data, $flags, $context) role.

The $filename parameter determines the file in which the information volition be written. The second parameter is the data that you lot want to write to the file. Most of the time information technology will be a cord, but information technology could besides be an assortment or a stream resource.

Remember that PHP will automatically create a file with the given proper noun for you if information technology doesn't already be. Nonetheless, it won't create any directories for you. This means that you lot tin can store a file with the name On the Origin of Species [Charles Darwin].txt without whatsoever mistake. However, setting $filename to Biology/Evolution/On the Origin of Species [Charles Darwin].txt, if Biological science/Development/ doesn't already exist, volition result in an error.

The $flags parameter determines how the content volition 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. Information technology 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 yous 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 2 different scripts are reading or writing data to the aforementioned file. With this particular value, you lot will go 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 imitation 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 considering code that writes 0 bytes to the file will notwithstanding evaluate to false.

Reading and Writing Data to Files

You can caput over to the Projection Gutenberg website and attempt to download files using the file_get_contents() function. Once you lot have the data in a cord, you lot tin also simply store it in a local file using the file_put_contents() function. The following example will brand this clear:

You could salvage webpages or content from websites like Wikipedia in a like style. If you need to make sense of the HTML or parse the HTML content that yous just saved locally, y'all can follow a tutorial like Parsing HTML With PHP Using DiDOM, which will assist yous in automatically getting links, image files, or whatsoever other such data from the webpage.

Permit's get back to local files now. Consider a situation where you have a agglomeration of text files and you desire to analyze their content to encounter things like the nigh common words in them. This could exist achieved easily using a agglomeration of congenital-in PHP functions.

Nosotros converted all the text to lowercase and fabricated the assumption that every single word breaks at spaces. The text is then converted to an assortment using explode() to arrive easier to analyze individual words. Surprisingly, the word "development" is not used even one time in the entire book that gave the theory of evolution its origin.

This was merely an example of automatically analyzing a large corporeality of text. You could do something similar with any kind of text stored in a file.

Logging Data With FILE_APPEND

One more than useful example would be logging data over small periods of fourth dimension. It could be your do routine, weather data, or a bee colony that you are observing. Once you have the data in a string, y'all tin easily store it in a file and append it to existing data using the FILE_APPEND flag with file_put_contents().

Similar code could be used for something like storing Wikipedia's featured article of the day in a file every solar day or keeping runway of news articles and headlines over the grade of weeks or months. All you need to do is write code to scrape the data and then shop it using something similar to the above code snippet. A tutorial like Parsing HTML With PHP Using DiDOM tin help you with the scraping part.

Instead of writing the text in plain format, y'all could wrap it in some HTML to make it easier to read in browsers. The possibilities are endless.

Final Thoughts

There are many other means of reading and writing information to files in PHP. However, file_get_contents() and file_put_contents() will address nearly all your bones needs without adding unnecessary complication.

The just time you might confront a problem with file_get_contents() is when the file you are reading is very big—like 2GB or more in size. This is considering file_get_contents() loads the whole file into memory at once, and in that location is a good chance of running out of retention with such big files. In that case, you will have to rely on functions like fgets() and fread() to read a small office of the file at once.

williamsmishe1945.blogspot.com

Source: https://code.tutsplus.com/tutorials/reading-and-writing-data-to-files-in-php--cms-32117

Belum ada Komentar untuk "How to Read a File Starting From a Specific Place Php"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel