使用JQuery和PHP将数据保存到文件中

时间:2016-03-18 08:38:30

标签: php jquery

我的问题是即使它“成功”保存,文件实际上也没有保存。 (我在Cloud9IDE上运行它)

我的文件夹导出设置为可通过chmod 777 -R ./进行读写。

有人可以向我解释为什么没有创建hello.txt文件,以及我可以做些什么来解决这个问题?

JQuery的

$("[data-action=save-file]").on("click", function(e) {
  var filename = "hello.txt"
  var content = "Hello world!"

  $.ajax({
    type: "GET",
    url: "submit.php",
    data: {
      "filename": filename,
      "content": content,
    },
    cache: false,
    success: function(msg) {
      console.log(msg)
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.log("Some error occurred")
    }
  })
})

PHP

<?php
  $filename = $_GET["filename"];
  $fp = fopen("anon/".$filename, "wb");
  if (!$fp) {
    echo getcwd();
    exit;
  } else {
    $outputstring = $_GET["outputstring"];
    fwrite($fp, $outputstring);
  }
  $fclose($fp);
?>

我也试过......

<?php
  $filename = $_GET["filename"];
  $outputstring = $_GET["outputstring"];
  file_put_contents($filename, $outputstring, FILE_APPEND | LOCK_EX);
?>

4 个答案:

答案 0 :(得分:1)

如果这是发布的实际代码,那么ajax发送的参数是“content”和“filename”,而php期望“outputstring”和“filename”,所以,在php端,有没有“outputstring”,程序不检查$ _GET中的“content”。

$filename = $_GET["filename"];
$outputstring = $_GET["content"];
file_put_contents($filename, $outputstring, FILE_APPEND | LOCK_EX);

GET(Max size of URL parameters in _GET)的参数也是最大长度,因此如果文件内容曾经是实际文件,则可能会被截断。尝试使用类型:“POST”而不是。

答案 1 :(得分:1)

也许你应该开始调试服务器端: 首先,使用file_put_contents时,检查它是否返回false(使用运算符===)。在这种情况下,文件夹anon/ doesn't exists。 第二步:使用is_writable检查该文件夹的writability

if (!isset($_GET[...], $_GET[...])) die("missing vars...");
if (!is_writable($filenamewithpath)) die("dir not writable");
if (file_put_contents(...) === false) die("dir doesn't exists");

如果目录不可写,请尝试使用chmod($path, 0777)。可能是你的主目录是0777而不是子目录。

顺便提一下,正如其他人指出的那样,你的ajax呼叫正在发送&#34;内容&#34;而不是&#34; outputstring&#34;作为参数。你应该重命名数据对象密钥。

还尝试使用绝对路径(例如使用__DIR__ . "/anon/". $filename);

答案 2 :(得分:0)

php $fp.close()中的代码是错误的。它应该是fclose($fp)

答案 3 :(得分:-2)

wb不是php中的任何模式。使用w +而不是wb

你需要检查文件夹是否存在

   $path = "anon";
   if (!file_exists($path) && is_dir($path))
   {
        if (!mkdir($path, 0777, TRUE))
        {
            return false;
        }
   }