Rahtid
Rahtid

Reputation: 13

Sending HTML form data to webserver via PHP

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!

Upvotes: 0

Views: 108

Answers (2)

Eduardo Estevez Nunez
Eduardo Estevez Nunez

Reputation: 183

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.

Upvotes: 2

Alex Hunter
Alex Hunter

Reputation: 260

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

Upvotes: 0

Related Questions