Saving Variable Value to a Text File Using PHP

by clicking on a button I am setting a variable in php using Ajax.

submitInfo(var1);

function submitInfo(var1)
{
  $.ajax({
        type: "POST",
        url: "js/info.php",
        data: {Info:var1},
        success: function (result)
        {
             alert(result);
        }
    });
}

in my php code, How can I save "var1" in a text file? I have used this to save variable in a text file but it is not saving anything there:

<?php
if (isset($_POST['var1']))
        {
            echo $_POST['var1'];
        }
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
?>


The first issue is that in your JQuery you actually assigning the var1 variable to 'Info' so the $_POST array will contain this rather than var1.

You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.

<?php
  $var1 = "";
  $filename = "js/test.txt";

  // Get the correct $_POST object
  if (isset($_POST['Info']) {
    $var1 = $_POST['Info'];
  }

  // If the variable is not empty try to write your file
  if (!empty($var1)) {
    if(!$file = fopen($filename,"w")) {
       $msg = "Cannot open file");
    } else if (fwrite($file,$var1) === false) {
      $msg = "Cannot write to file");
    } else {
      $msg => 'all was good'
    }

    fclose($file);

    $result = array(
      'error' => 'false',
      'msg' => $msg
    );
  } else {
    $result = array(
      'error' => 'true',
      'msg' => 'Info was empty'
    );
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";

PS: Not tested this so fingers crossed there are no typos.