Web Programming TutorialsPHP File Create/Write

PHP File Create/Write

We have already learned the basics of file handling, such as opening, creating, closing and reading a file. Today we will learn how to write to a file in this PHP File Create/Write tutorial.

  • Writing to a file:
    • We can write into a file using fwrite() function.
    • It takes 3 parameters,
      1. The file pointer that points to the file in which we want to write.
      2. The string to be written in the file.
      3. The number of bytes that must be written at a time in the file. It is optional. If the number of bytes is not provided, the whole given string will be written into the file.
    • If we want the statements provided in the string be written each on a new line, a new line character (\n) should be used there.
    • Remember, windows require a carriage return character as a new line character, so to provide new line in windows the new line character to be used is \r\n.
    • So let us go through an example that writes some data to a file:
    • To demonstrate it, create a new folder named as file_write folder in the htdocs folder in xampp folder located in C drive. Then open a new notepad++ document and save it as index.php in this newly created file_write folder.
    • The code is given below:
    • <html>
      <head>
      <title>Write into File using PHP</title>
      <style>
      	.decor{
      	      padding:20px;
      		color:red;
      		font-size:25px;
      		font-width:bold;
      	}
      </style>
      </head>
      <body>
      <h1>Use of fwrite() function to write to a file</h1>
      
      <?php
      	if(!($fp=fopen("fileinfo.txt","w")))
      	{
      		echo '<p class="decor">Problem in creating the file!</p>';
      	}
      	else
      	{
      		//string to be written
      		$string="File handling in PHP is mostly similar to file handling in standard C language.\r\n";
      
      		//use of fwrite() function to write to file
      		fwrite($fp,$string);
      		
      		//string to be written
      		$string="PHP provides various tools for creating, uploading and editing files.\r\n";
      
      		//use of fwrite() function to write to file
      		fwrite($fp,$string);
      		
      		echo '<p class="decor">Write Completed!</p>';
      	}
      	fclose($fp);
      ?>
      </body>
      </html>
      
    • We now know very well that we can create a file using fopen() function in any mode we want.
    • In the above code, we have created a new file named info.txt in write mode “w” using fopen() function.
    • If any error occurs in creating this file, fopen() function will return value 0 (zero) which represents false and display the statement Problem in creating the file!
    • If the file has been created successfully, then the process of writing data to the file is carried on in the else part of the if-else statement.
    • A variable $string is declared and a string is assigned to it.
    • This string is written to the file info.txt using the fwrite() function as shown below:
    • fwrite($fp,$string);
    • Here, we have $fp and $string as parameters to fwrite() function. $fp is the file pointer pointing to info.txt file and $string contains the string to be written into the file. Here the number of bytes parameter is omitted, so the complete string will be written to the file.
    • One more time another string is written in the same way to info.txt file.
    • After completing the write process the statement Write Completed! is displayed using echo function.
    • At last the file is closed using fclose() function.
    • Now open the browser and type localhost/file_write in its address bar and see the following output:
    • write_to_file_in_w_mode_using_fwrite
      fig 1

    • The created file is stored in the folder file_write created on server.
    • The file contents are shown below:
    • file_contents_written_in_w_mode
      fig 2

  • Appending data to a file:
    • Appending data to a file means, adding information to an existing file by retaining its original data.
    • To append data to an existing file, the file should be opened in append mode “a”.
    • Let us append data to our existing info.txt file and read it in the same program.
    • This can be done by opening the file info.txt in “a+” mode i.e. read/append mode.
    • The code is given below:
    • <html>
      <head>
      <title>Write into File using PHP</title>
      <style>
      	.decor{
      		padding:20px;
      		color:red;
      		font-size:25px;
      		font-width:bold;
      	}
      </style>
      </head>
      <body>
      <h1>Use of fwrite() function to write to a file</h1>
      
      <?php
      	//opening file in a+ mode and writing to it
      	if(!($fp=fopen("fileinfo.txt","a+")))
      	{
      		echo '<p class="decor">Problem in creating the file!</p>';
      	}
      	else
      	{
      		$string="You need to be very careful while dealing with files, because you can harm the file data if something goes wrong.\r\n";
      		
      		$string.="Any information written in the file is temporarily written in the buffer and is then later stored on the hard-disk when the file is saved.\r\n";
      		
      		fwrite($fp,$string);  //write string to file info.txt
      		
      		rewind($fp);  //move the file pointer to the start of the file
      		
      		while(!feof($fp)) 
      		{
      			$s=fgets($fp);
      			echo $s."<br>";
      		}
      	}
      	fclose($fp);
      ?>
      </body>
      </html>
      
    • In the above code, we are trying to append some more text at the end of info.txt file. We are also going to read the file after appending data to it.
    • So we have opened the existing file info.txt in read/append mode i.e. “a+”, in which we can append data as well as read the data in the file.
    • The data to be written to file in stored in $string variable.
    • It is then written to file using fwrite() function in which the file pointer $fp and the variable containing the data i.e. $string are passed as parameters.
    • With this we finished writing data below the existing data i.e. our file pointer is now at the end of file.
    • Now we want to read the file from the beginning. It means the file pointer should point at the start of the file.
    • This is done using function rewind(). The function rewind() takes the file pointer as its parameter and forces it to point at the start of the file, no matter where it is. The statement using rewind() function is shown below:
    • rewind($fp);
    • Now when the pointer points at the start of the file we can now read the data very easily using fgets() function in a while loop as shown below:
    • while(!feof($fp)) 
      {
      	$s=fgets($fp);
      	echo $s."<br>";	
      }
      
    • Here, the EOF is checked using feof() function every time.
    • If file has not reached its end, one line from the data is read from the file using fgets() function, stored in variable $s and displayed using echo function.
    • The html break statement is used in echo function so that every line should be displayed on a new line.
    • The process continues till EOF has not reached, and ends when EOF is reached.
    • After the whole data in the file has been read and displayed, the file is closed using fclose() function.
    • The output is shown below:
    • file_written_and_read_using_a+_mode
      fig 3

    • If you compare this fig 3 with fig 2, you will notice that the original info.txt file had only first 2 statements and the next 2 statements have been added using a+ mode later.
    • In the similar way, we can use r+, w+, etc. modes to perform reads and writes with files.
  • Some more functions used for file handling:
  • Function Syntax Description
    fread() fread(file_pointer,number of bytes to read); The function fread() reads number of bytes specified from the file pointed by file pointer.
    readfile() readfile(“filename”); The function readfile() reads the file passed to it as a parameter and outputs it to output buffer.
    copy() copy(file,file_to); It copies the first file contents to the second file. Returns true on success and false on failure.
    dirname() dirname(“path”); It returns the directory name component from the given path.
    ftell() ftell(filename); It returns the current file pointer position in the given file otherwise returns false on failure.
    is_dir() is_dir(filename); Checks whether the file is a directory.
    is_file() is_file(filename); Checks whether the file is a regular file.

    table 1

Thus we learned how to write into a file and then read from the file along with introduction to some more functions dealing with file handling in this PHP File Create/Write tutorial.

Previous articlePHP File Upload
Next articlePHP File Handling

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -