0

I have a problem with my php code, I am a beginner and i need some help. I tried to make a function that is going to write in a file the input text from 3 variables using write, but it seem that when I am putting everything into a function it is not working.

Here is my code:

<!doctype html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<form action="test.php" method="post">
<input type="text" name="text">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="submit" value="write">
</form>
<?php



$text = $_POST['text'];
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
function start($text,$text1,$text2)
{
    if(isset($_POST['submit']))
    {
        $text_total = "$text $text1 $text2 \r\n";
        $file = fopen("text.txt", "a+");
        fwrite($file, $text_total);
        fclose($file);
    }
}

start();

?>
<body>
</body>
</html>
Paul Lo
  • 6,032
  • 6
  • 31
  • 36

3 Answers3

3

passing your string parameters to the function call

 <?php


    $text = $_POST['text'];
    $text1 = $_POST['text1'];
    $text2 = $_POST['text2'];
    function start($text,$text1,$text2)
    {
        if(isset($_POST['submit']))
        {
            $text_total = "$text $text1 $text2 \r\n";
            $file = fopen("text.txt", "a+");
            fwrite($file, $text_total);
            fclose($file);
        }
    }

    start($text,$text1,$text2);

    ?>
underscore
  • 6,495
  • 6
  • 39
  • 78
0

Your function argument is missing is your problem. Also check the form is submitted. It's for better practice.

<?php

function start($text,$text1,$text2)
{
  if(isset($_POST['submit']))
  {
    $text_total = "$text $text1 $text2 \r\n";
    $file = fopen("text.txt", "a+");
    fwrite($file, $text_total);
    fclose($file);
 }
}

if(isset($_POST['submit'])){

  unset($_POST['submit']); //This is to make sure it's executed one time only

  $text = $_POST['text'];
  $text1 = $_POST['text1'];
  $text2 = $_POST['text2'];
  start($text,$text1,$text2);
}


?>
Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25
-1

You have to add this on the test.php file:

<?php



$text = $_POST['text'];
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
function start($text,$text1,$text2)
{
    if(isset($_POST['submit']))
    {
        $text_total = "$text $text1 $text2 \r\n";
        $file = fopen("text.txt", "a+");
        fwrite($file, $text_total);
        fclose($file);
    }
}

start();

You cant have it together with the html

Emmanuel Orozco
  • 369
  • 1
  • 10