File add contents php

How to write into a file in PHP?

It creates the file lidn.txt , but it’s empty. How can I create a file and write something into it, for example the line «Cats chase mice»?

9 Answers 9

You can use a higher-level function like:

file_put_contents($filename, $content); 

which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.

Just a sidenote, file_put_contents() works in PHP5 only. Doesn’t seem like a problem in this case (your answer got accepter, after all), but there might still be a few hosts out there running PHP4.x .

A very important sidenote: file_put_contents() is a memory nightmare in comparison to fopen(). I love to use it but when handling large files you want to be able to «stream» data into it. PHP will require a large multiple of final filesize as internal memory, so keep that in mind when using this function. For smaller amounts of data I’d recommend it for it’s easy usage.

Then use file_put_contents($filename, $other_stream). It’s the same as using stream_copy_to_stream-), which is very memory efficient.

@Xsmael Not in the distant past of 2009 😉 PHP7 wasn’t around back then. But yeah, put_file_contents() was first introduced in PHP5, and has been included since, in later versions as well.

@sathish after writing to the file like above how do we read the file without closing the file ( fclose($fp) ), I tried with $fp = fopen(‘lidn.txt’, ‘w+’); , $fp = fopen(‘lidn.txt’, ‘a+’); but neither of them worked

$fp = fopen('lidn.txt', 'w'); fwrite($fp, 'Cats chase'); fwrite($fp, 'mice'); fclose($fp); 
$text = "Cats chase mice"; $filename = "somefile.txt"; $fh = fopen($filename, "a"); fwrite($fh, $text); fclose($fh); 

after writing to the file like above how do we read the file without closing the file ( fclose($fh) ), I tried with $fh = fopen(‘lidn.txt’, ‘w+’); ,` $fh = fopen(‘lidn.txt’, ‘a+’); ` but neither of them worked

$fp = fopen('lidn.txt', 'w'); fwrite($fp, 'Cats chase mice'); fclose($fp); 
  1. Open the file
  2. Write to the file
  3. Close the file

$select = "data what we trying to store in a file"; $file = fopen("/var/www/htdocs/folder/test.txt", "w"); fwrite($file, $select->__toString()); fclose($file); 

I use the following code to write files on my web directory.

write_file.html

write_file.php

This is a working script. be sure to change the url in the form action and the target file in fopen() function if you want to use it on your site.

I just started writing php but this looks like you are not just writing a text file, but you are writing a php code file onto your server, which could then be run immediately after by referencing the «demo.php» URL. Someone could write malicious PHP code to your server and immediately execute it, right? I assume this is so you could test your own codes but people should be warned of the risks of this particular implementation. (That being said, I like it and will us it myself)

In order to write to a file in PHP you need to go through the following steps:

  1. Open the file
  2. Write to the file
  3. Close the file
$select = "data what we trying to store in a file"; $file = fopen("/var/www/htdocs/folder/test.txt", "a"); fwrite($file , $select->__toString()); fclose($file ); 

fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead. Article

The file_put_contents writes a string to a file.

This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.

The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length, whichever comes first.This function returns the number of bytes written or FALSE on failure.

Источник

How to Append to a File With PHP

Monty Shokeen

Monty Shokeen Last updated Aug 14, 2021

Data is usually stored in a database when people are creating their website. However, sometimes we need to store data in files to make it easier for people to read or modify at a later time.

PHP comes with a lot of functions to read and write data to a file. We can also use a few of them to append data to a file. In this tutorial, you’ll learn two different ways of appending data to a file with PHP.

Understanding the file_put_contents() Function

The file_put_contents() function is one of the easiest ways to write data to a file with PHP. It accepts four different parameters that determine its behavior. These parameters are:

  • filename : the path to the location of the file to which we want to write our data.
  • data : specifies the data that you want to write to the file. It is usually a string, but you can also specify an array or a stream resource. The function will automatically implode the contents of a single dimensional array with implode() in order to write the data to a file.
  • flags : controls the behavior of file_put_contents() . There are three different flags that you can set here, either by themselves or in combination with other flags. Different flags can be combined using the | operator.
  • context : useful only in providing additional data to PHP when you are reading or accessing content from a stream.

Using file_put_contents() to Append Data to a File With PHP

The default behavior of the file_put_contents() function is to overwrite the contents of a given file with any new data you provide. This is not desirable when you want to preserve the old data and add some new data. In such cases, you can use the FILE_APPEND flag to let PHP know that it should append data at the end of content originally present in the file.

Under some special circumstances, you might be appending data to a file from multiple scripts at the same time. In these situations, it is advisable to get an exclusive lock on the file using the LOCK_EX flag. This can help prevent data corruption or some other unexpected behavior. When you use this flag, other scripts will wait for the current process to complete writing to the file before they append their own data.

Here is an example in which some text is appended to an existing file using file_put_contents() .

// Original File: Canada is a country in North America. . bi-national land border. 
// File Contents After this Line: Canada is a country in North America. . bi-national land border. Canada's capital is Ottawa, 
file_put_contents('canada.txt', " Canada's capital is Ottawa,", FILE_APPEND | LOCK_EX); 
// File Contents After this Line: Canada is a country in North America. . bi-national land border. Canada's capital is Ottawa, and its three largest metropolitan areas are Toronto, Montreal, and Vancouver. 
file_put_contents('canada.txt', " and its three largest metropolitan areas are Toronto, Montreal, and Vancouver.", FILE_APPEND | LOCK_EX); 

In the above example, we wrote some strings to a file called canada.txt which contains information about Canada. Both the string were appended at the end of the file one after the other.

Keep in mind that this function will create a file if one doesn’t already exist. However, it won’t create a non-existent directory. So it might be a good idea to check if a file exists before you start writing to it.

Using fwrite() to Write Data to a File With PHP

Using the file_put_contents() function to write data to a file with PHP is similar to calling fopen() , fwrite() , and fclose() in that order. This means that doing multiple write operations on the same file can be inefficient because we are constantly opening and closing the file again and again.

One way to overcome this issue is to call these functions yourself. Just begin by calling fopen() at the start of the write operation. After that, write content to the file as many times as you like with the fwrite() function. In the end, you can simply call fclose() to close the file handle. Let’s discuss each of these steps in detail now.

The fopen() function accepts four different parameters that you can use to tell PHP how it should open a file.

  • filename : the name of the file that you want to open.
  • mode : the mode for opening a file can be specified using either one or two characters. We want to open the file and then append some text to it. To append, set the mode with the character a or a+ . This will place the file pointer at the end of the file. PHP will also try to create the file if it doesn’t already exist. When files are opened with the a+ mode, you can also read the contents of the file.
  • use_include_path : instructs PHP to look for files inside the specified include path as well. Defaults to false.
  • context : useful only in providing additional data to PHP when you are reading or accessing content from a stream.

Now that the file is open, we can use the fwrite() function to add information to the file. fwrite() takes three parameters:

  • resource : this is the resource handle we created earlier with fopen() .
  • string : the text that you want to append to your file.
  • length : is optional and it is used to set the maximum number of bytes that should be written to the file.

You can close the file handle by using the fclose() function once you have completed all your write operations.

Here is an example that shows you how to use fopen() , fwrite() , and fclose() to append data to a file.

Источник

Читайте также:  Python php and javascript
Оцените статью