PHP File Write function

$body_content="This is my content"; //To store inside the file $file_name="test_file.txt"// file name // Open the file in write mode, if file does not exist then it will be created. $fp = fopen ($file_name, "w"); fwrite ($fp,$body_content);// entering data to the file fclose($fp);// closing the file pointer
chmod($file_name,0777);// changing the file permission. ?>
File create or Write We can write to a file by using fwrite() function PHP. Please note that we have to open the file in write mode and if write permission is there then only we can open it in write mode.

If the file does not exist then one new file will be created. We can change the permission of the file also. However we can check the presence of a file by using file_exists function.
Read the content of a file by using fopen()
We can use fwrite() to write counter and many other scripts if you are not using any database for storing data. . Here we will see how to write to a file.

Reading and Writing content to a file

We can read the content of a file and then apply required changes to it and save the same file.

We can apply search and replacement of content by using str_replace and then save the file with changed content.

Here is the code
$filename=$_GET['file_name']; // To get the file name from URL 
//$filename='test.php'; // file name is stored

$fd = fopen ($filename, "r"); // opening the file in read mode
$contents = fread ($fd, filesize($filename)); // reading the content of the file
fclose ($fd);                                // closing the file pointer
$search=array("<h3>","</h3>","<br />");

$fd = fopen ($filename, "w"); // opening the file in write mode
//echo $contents;               // printing the file content of the file
fwrite ($fd,$contents);        // entering data to the file
chmod($filename,0777);       // Setting the write permission 

/// Opening the file in a new window and closing again ///// 

echo "

Page Hit counter Script

Create one page hit counter where a incremental number is stored in a text file each time the file is opened..

File Directory Functions File Delete
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer