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

Read and Write file in PHP


PHP PHP 
Ratings:
0 Comment(s)
 2220  View(s)
Rate this:

Read and Write file in PHP

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().


Don't want to miss updates? Please click the below button!

Follow MindStick