如何使用html输入并使用输入的上下文命名txt文件?


How do I take an html input and name a txt file with the context of the input?

我正在制作一个类似粘贴的网站,我将采用两个输入字段,如:

<form name="form1" method="post" action="paste.php">
 Title: <input type="text" name="title"><br>
 Paste: <input type="text" name="paste"><br>
 <input type="submit" name="Submit" value="Paste Me"> 
 </form>

,我需要将数据写入文件,如下所示:

<?php
$title = $_POST['title'];
$paste = $_POST['paste'];
$fh = fopen("[name variable here].txt", "w");
fwrite($fh, $paste);
fclose($fh);
print "The paste has been submitted.";
?>

但是在$fh行中,我需要知道如何从"title"中获取输入,并创建一个包含"paste"输入内容的新txt文件。我该怎么做呢?

所以你想要的是:

$fh = fopen("{$_POST['title']}.txt", "w");

或:

$fh = fopen($_POST['title'] . ".txt", "w");

但是这真的是一个坏主意,因为有人可以摆弄title变量并给它这样,你覆盖了一个重要的文件!

为了使用$_POST['title']变量作为文本文件的名称,您将这样做(您已经将POST数组的值分配给$title) -

$fh = fopen($title.".txt", "w");

正如其他人提醒您的那样,请确保验证和清理来自用户的数据。

我建议使用一些框架,如Symfony2或Zend2来创建您的网站。它提供了许多工具,如验证、表单控制、缓存、数据库/orm等。但是,如果你想用纯PHP做,尝试像$fileName = preg_replace('/[^A-Za-z0-9_'-]/', '_', $title);和记住:永远不要保存原始内容从互联网未经验证。