PHP Creating And Writing File


PHP Creating And Writing File:– One of the most useful features of a server side language is its ability to interface with the file system on the server.
o access a file you first have to establish a connection to that file. This is done by opening the file with the fopen function. To use the fopen function you provide it two parameters. The first is the name of the file you wish to use and the second says how you want to use the file (for reading or writing etc) Using the fopen function establishes a pointer to the file

When we have an existing file then we open it to perform operations and if file does not exists then we create it first.


PHP Creating And Writing File | Example

Below first screenshot shows the initial content of file and second bottom screenshot shows content of file after writing into file.

Example

<?php 
$data="Hi John....";
$filedata="Hi Alex"...;
$value="Hi Adam....";
if(file_exists("file.txt")){
$handle = fopen("file.txt", "w");//open file in read mode 
echo $handle;
}
else {
	die("Error: The file you are trying to access doesn't exist.");
}
//echo fread($handle,"10");
echo "<br>";
echo "<br>";
//echo fread($handle,filesize("file.txt"));
fwrite($handle,$data);
fwrite($handle,$filedata);
fwrite($handle,$value);
fclose($handle);
$myfile = fopen("testfile.txt", "w");
echo "data has been successfully written";
?>    

PHP Filesystem Functions

Example

Functions Description
fread() Reads a string of characters from a file.
fwrite() Writes a string of characters to a file.
rewind() Moves the file pointer to the start of the file.
ftell() Returns the position of the file pointer.
fseek() Moves the file pointer to a specific location within an open file.
readfile() Displays the contents of a file without needing to open it.
fpassthru() Displays the contents of an open file.
file_put_contents() Writes a whole string to a file without needing to open it.
file_get_contents() Reads an entire file into a string without needing to open it.
file() Reads an entire file into an array.
fgetcsv() Reads a line of comma – separated values.
fgets() Reads a single line at a time.
feof() Checks to see if the end of the file has been reached.
fgetc() Reads a single character at a time.

Advertisements

Add Comment

📖 Read More