0

I am trying to write contents to a file with user submitted data. I have some text say "my name is" and after this text i want to write user submitted value. How do i do this? I trying to do this with code given below.

<?php
  $fname=$_POST['fname'];
  $lname=$_POST['lname'];
  $my_file='file.txt';
  $handle= fopen($my_file,'w+');
  $data= 'My fname is $name and My lname is $lname';
  $fwrite($handle,$data);
?>

When i run this code $name does not take the input value and writes as $name like

"My name is $name"

How to fix this?

6 Answers6

0

To get a PHP variable to output, you need to use double quotes.

$data= "My name is $name";

or

$data = 'My name is '.$name;
Albzi
  • 15,431
  • 6
  • 46
  • 63
0

Try this:

<?php
$name=$_POST['name'];
$my_file='file.txt';
$handle= fopen($my_file,'w+');
$data= 'My name is ' . $name;
$fwrite($handle, $data);
?>
0

You need to access the variable $name while writing the name to the file. The way you are doing it now does not add the value of the variable in the string. To do so you can change :

$data= 'My fname is $name and My lname is $lname';

to

$data= "My fname is $name and My lname is $lname";

The double quotes substitute the value of the variables in the string literal as it is evaluated before it is used in the expression. For more info refer this answer.

or

$data= 'My fname is '.$name.' and My lname is '.$lname;

Here, the string literal is concatenated with the value of the variables using the . operator.

Community
  • 1
  • 1
bluefog
  • 1,894
  • 24
  • 28
0

You have to concat your string with variable.

<?php
  $name=$_POST['name'];
  $my_file='file.txt';
  $handle= fopen($my_file,'w+');
  $data= 'My name is '.$name;
  $fwrite($handle,$data);
  $fclose($handle);
?>
Szaby
  • 39
  • 3
0

In PHP, variable returns value only in double quoted, single quote treat it as string.

Vegeta
  • 1,319
  • 7
  • 17
0
<?php
     $fname=$_POST['fname']; 
     $lname=$_POST['lname'];
     $my_file='file.txt';
     $handle= fopen($my_file,'w+');
     $data= "My fname is $name and My lname is $lname"; // Change the quote from single to double. for php to parse and replace the variable with it's value but single quote is a literal
      $fwrite($handle,$data);
?>
lightup
  • 634
  • 8
  • 18