php - How can I save data from a html form in a file? -
this question has answer here:
- how put string text file in php? 2 answers
i did simple form.in trying modifying $_post output.
<?php $lhs = array(); $rhs = array(); foreach($_post $key => $value) { echo $key . "=" . $value; echo "<br>"; $lhs[] = $key; //first array left hand side $rhs[] = $value; //second array right hand side } ?> <form name="form1" method="post" action=""> name: <input type="text" name="name"><br> phone no: <input type="text" name="phone" /><br/> course:<input type="text" name="course" /> <br /> <input type="submit" name="submit" value="sign up"> </form> so output of be:
name=xyz phone=123455453 course=be submit=sign now can observe see getting output of button also:
submit=sign which don't require in output. , require output this:
name=xyz phone=123455453 course=be this output want store in text file.
i not able modify output either not able store output in text file.
how can rid of submit button output , save data file?
any or advice appreciated , in advance.
this should work you:
here first added if statement check if submit button pressed isset() , fields aren't empty().
in foreach loop added if statement check if current key submit button , if yes skip iteration continue.
to save data file used file_put_contents() go through both arrays array_map() , return key/value pair combined elements new line character (php_eol) @ end of each element.
<?php if(isset($_post["submit"]) && !empty($_post["name"]) && !empty($_post["phone"]) && !empty($_post["course"])) { foreach($_post $key => $value) { if($key == "submit") continue; echo $lhs[] = $key; //first array left hand side echo $rhs[] = $value; //second array right hand side } file_put_contents("file.txt", implode(php_eol, array_map(function($v1, $v2){ return "$v1:$v2"; }, $lhs, $rhs)), file_append); } ?> <form name="form1" method="post" action=""> name: <input type="text" name="name"><br> phone no: <input type="text" name="phone" /><br/> course:<input type="text" name="course" /> <br /> <input type="submit" name="submit" value="sign up"> </form>
Comments
Post a Comment