php 如何从浏览器创建文件

php how to create file from browser

当用户点击提交时,我正在尝试创建一个文件。

Centos 7

php 7.2

我试过用几种不同的方式修改代码也试过file_put_contents似乎没有用。

代码: index.php

<form action="sendmail.php" method="post">
<input type="text" placeholder="fname" name="fname">
<button type="submit">submit</button>
</form>

sendmail.php:

<?php
$fname = $_POST["fname"];
echo "bef: " . $fname;
$myfile = fopen("/signupemails/" . $fname . ".txt", "w") or die("Unable to open file!");
echo "aft: " . $fname;
$txt = $fname;
fwrite($myfile, $txt);
fclose($myfile);
?>

创建文件的目录

[root@webserver webdir]# ll -d /signupemails/
drwxrwxrwx. 2 apache apache 51 Aug 25 20:41 /signupemails/

如果我更改 sendmail.php 并对 $fname 和 运行 php sendmail.php 进行硬编码,它将创建文件

从浏览器创建它我得到 "Unable to open file!"

尝试更改此行:

$myfile = fopen("/signupemails/" . $fname . ".txt", "w") or die("Unable to open file!");

PHP 与 JavaScript 的 logical "or" semantics 不同。该表达式 returns 是一个布尔值,因此 $myfile 将等于 true 而不是文件句柄。

这样写:

$myfile = fopen("/signupemails/" . $fname . ".txt", "w");
if (!$myfile) die("Unable to open file!");

我建议用js做 例如


function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

你的代码应该可以正常工作,我刚刚测试过它似乎工作正常。

是否禁用了selinux?