Search code examples
phppostgetfwriteisset

PHP fwrite and variable isset


I'm working on a website where the user is going to fill in a form, and the form will be printed out to a .txt file.

Everything works fine, but I would like to know how i can make it so when a user leaves one input box empty, it won't be shown in the text file.

My code (index.php):

<form action="sendinfo.php" method="post">
Your Name:<br />
<input type="text" name="name"><br />
Your Message:<br />
<textarea name="message"></textarea><br />
<input type="submit" value="Send Info">
</form>

My code(sendinfo.php)

    <?php
    //variables
    $name = $_POST['name'] >
    $message = $_POST['message'] 

    //code i need to know
    if (!isset()){

    }
    ?>

    <?php
        //write text file.
        $file = fopen("Test.txt","w");
        fwrite($file, "Name: " . $name . "\r\n");
        fwrite($file, "Message: " . $message . "\r\n");
    ?>

Solution

  • You think too complicated. Try this:

    <?php
    
    //variables
    $name = $_POST['name'];
    $message = $_POST['message']; 
    
    //write text file.
    $file = fopen("Test.txt","w");
    if ($name) fwrite($file, "Name: " . $name . "\r\n");
    if ($message) fwrite($file, "Message: " . $message . "\r\n");
    ?>
    

    Reason why this works is how php treats such condition: it will resolve the expression to false for anything "falsy", so a variable that is not set, an empty variable and a variable that contains false or null. For everything else the expression will resolve to true, thus the entry will be written.