在PHP中创建新文件并更新这些创建文件的列表
问题描述:
我正在试图制作一个网站,它将动态地保存RPG角色表。我希望能够通过提交与纸张的标题形式,像这样来创建新角色时(这是index.php页面的一部分):在PHP中创建新文件并更新这些创建文件的列表
<form action = "charCreate.php" method = "post">
<h1>Character Sheet Name:</h1>
<input type = "text" name = "fileName">
<input type = "submit" value="Submit">
</form>
我知道则fopen方法,但我不确定如何在这种情况下使用它。我希望能够使用这种形式创建新的网页,并让index.php显示使用上述表单创建的文件列表。
什么是动态更新已创建网页列表并创建这些网页的最佳方式,使用表单中的值作为文件名。
我也想知道如何改变这些新创建的页面,但我需要先弄清楚这一点。
谢谢。
答
执行以下操作:
<?php
// w will create a file if not exists
if($loHandle = @fopen('folder_to_add_files/'.$_POST['fileName'], 'w'))
{
echo 'Whoops something went wrong..';
}
else
{
// you can write some default text into the file
if([email protected]($loHandle, 'Hello World'))
{
echo 'Could not right to file';
}
@fclose($loHandle);
}
?>
当心你的文件名空间和其他怪异字符。 你可以像这样用str_replace函数替换空格:
// Replace spaces with underscores
$lstrFilename = str_replace(' ', '_', $_POST['fileName']);
要显示在index.php文件,你可以做到以下几点:
<?php
if ($loHandle = @opendir('folder_to_add_files'))
{
echo 'Directory handle: '.$handle.'<br />';
echo 'Entries:<br />';
// This is the correct way to loop over the directory.
while (false !== ($lstrFile = @readdir($loHandle)))
{
echo $lstrFile.'<br />';
}
@closedir($loHandle);
}
?>
答
这里的第一个,也是最重要的一点是,你会遇到试图管理文件中数据的可伸缩性/数据损坏问题 - 这就是数据库的用途。
仅使用平面文件来存储数据就可以构建大型,快速的系统,但这需要大量复杂的代码来实现复杂的文件锁定队列。但是考虑到简单地使用数据库的替代方案,很少值得付出努力。
允许用户指定文件名意味着他们将能够清除您的机器上的webserver uid可写入的任何文件。他们也将能够部署自己的PHP代码。不是一个好主意。
对于一个快速和肮脏的解决方案(这将在未来某些时候以可怕和痛苦的方式失败......)。
function write_data($key, &$data)
{
$path=gen_path($key);
if (!is_dir(dirname($path)) {
mkdir(dirname($path), 0777, true);
}
return file_put_contents($path, serialize($data));
}
function get_data($key)
{
$path=gen_path($key);
return unserialize(file_get_contents($path));
}
function gen_path($key)
{
$key=md5($key);
return '/var/data/' . substr($key,0,2) . '/' . substr($key,2) . '.dat';
}