0

I'm currently working on some webform. This form is supposed to send collected data to txt file on webserver, but somehow it gives me error.

Form:

<form action="my_webserver_path_to_script.php" name="form" method="post">
    <div>
        <label for="name">Name</label>
        <input name="name" type="text" id="name" placeholder="Your Name" required/>
    </div>
    <div>
        <label for="city">City</label>
        <input name="city" type="text" id="city" placeholder="Where do you live?" required/>
    </div>
    <div>
        <label for="sex">Sex</label>
        <select name="sex" id="sex" required>
            <option value="" selected disabled hidden>Your sex</option>
            <option value="man">Man</option>
            <option value="woman">Woman</option>
        </select>
    </div>
    <div style="margin-top: 30px; text-align: center;">
        <input class="button" type="submit" value="Join Us!"/>
    </div>
</form>

Script:

<?php
    if(isset($_POST['name']) && isset($_POST['city']) && isset($_POST['sex'])) {
        $data = $_POST['name'] . '-' . $_POST['city'] . '-' . $_POST['sex'] . "\n";
        $ret = file_put_contents('my_webserver_path_to_data.txt', $data, FILE_APPEND | LOCK_EX);
        if($ret === false) {
            die('There was an error writing this file');
            }
            else {
            echo "$ret bytes written to file";
        }
    }
    else {
        die('no post data to process');
        }
?>

When i fill all the fields and click submit it jumps to php address and prints 'There was an error writing this file'.
I've already read: questions/35443812 and questions/14998961
Usually, i don't respond between 16:00 and 08:00.
Thanks in advance!

Rahtid
  • 13
  • 4

2 Answers2

2

The "file writing error" is mainly caused by an incorrect permissions setting in your hosting provider. Probably , you have to set up the 775 permission to write the file. This link could be useful for you https://unix.stackexchange.com/questions/35711/giving-php-permission-to-write-to-files-and-folders

About your PHP code. My suggestion is to improve the line #1 with the follow code:

<?php
    if ( isset( $_POST['submit'] ) ) {
    }
?>

Regards, Ed.

  • I've thought about problem with permisson, but i can't check that until monday. You mean i should abbreviate whole script with the line you've sent? – Rahtid Sep 15 '17 at 13:04
  • It *is* possible to send the form without all the inputs he needs. It's better to explicitly check for what he needs. You might make it a bit cleaner like this though: `if(isset($_POST['name'], $_POST['city'], $_POST['sex'])) {` – ishegg Sep 15 '17 at 13:14
  • All of the 2 inputs, and select are necessary. I've changed the line you suggested. – Rahtid Sep 15 '17 at 13:27
0

simply type in the php $name= $_POST['name']; $city= $_POST['city']; $sex= $_POST['sex']; . If you type echo $name; you can see the data

Alex Hunter
  • 212
  • 9
  • 30