blog

Home / DeveloperSection / Blogs / Read and Write file in PHP

Read and Write file in PHP

Anonymous User4539 30-Nov-2011
Write to File from PHP:

From PHP you are able to open up a file on your server and write to it. If the file does not exist then we can create it, however if the file already exists then you must open in append mode so it will be writable. When writing to a file, the first thing you need to do is to open up the file. We do that with this code:

 <?php
                  // Store file name
                    $fileName = "YourFile.php";
                    // Open the file
                    $handle = fopen($fileName, 'w');
                    // Write the file
                    fwrite($handle, "Your String Value");
                    // After successfuly wrting close the file
                    fclose($handle);
            ?>
Read a File from PHP:

Reading a file is even easier. You could go through the fopen() method but I'm going to show you an easier way:

<?php
                // Store file name
                    $fileName = "YourFile.php";
                // Read the file content
                    $fileText = file_get_contents($fileName);
               
        ?>

Note:  If you opened the file using fopen() method then you have to close it using fclose().


Updated 18-Sep-2014
I am a content writter !

Leave Comment

Comments

Liked By