PHP write to file


Answers ( 1 )


    This question is about how to write data to a file using PHP, a popular server-side scripting language used for web development.

    In PHP, writing to a file is commonly achieved using several functions, the most prominent of which are fwrite(), file_put_contents(), and fopen() in combination with fwrite() and fclose(). Here are examples and explanations for each method:

    Using fwrite() with fopen() and fclose()

    1. Open the file - Use fopen() to open the file for writing. If the file does not exist, it will be created.
    2. Write to the file - Use fwrite() to write data to the file.
    3. Close the file - Use fclose() to close the file after writing.
    $file = fopen("example.txt", "w") or die("Unable to open file!");
    $txt = "Sample text to write in file\n";
    fwrite($file, $txt);

    Using file_put_contents()

    This is a simpler approach where you can write data to a file in one line. If the file does not exist, it will be created.

    file_put_contents("example.txt", "Sample text to write in file\n");

    Appending to a File

    If you want to append data to a file instead of overwriting, you can use the a mode in fopen() or the FILE_APPEND flag in file_put_contents().

    // Using fopen
    $file = fopen("example.txt", "a") or die("Unable to open file!");
    $txt = "Additional text\n";
    fwrite($file, $txt);
    // Using file_put_contents
    file_put_contents("example.txt", "Additional text\n", FILE_APPEND);

    Error Handling

    It's important to handle errors, such as when a file cannot be opened for writing. This can be done using or die() to display an error message, as shown in the examples, or by using a more sophisticated error handling mechanism like try-catch blocks.

    These are the basic methods for writing to files in PHP. The choice of method depends on the specific requirements of your application, such as whether you need to append to the file or overwrite it, and how much control you need over the file writing process.

Leave an answer