在PHP中创建新文件并更新这些已创建文件的列表
我试图使一个网站,将举行RPG字符表动态。我希望能够通过提交带有表单标题的表单来创建新的字符表单,如下所示(这是index.php页面的一部分):在PHP中创建新文件并更新这些已创建文件的列表,php,html,file,Php,Html,File,我试图使一个网站,将举行RPG字符表动态。我希望能够通过提交带有表单标题的表单来创建新的字符表单,如下所示(这是index.php页面的一部分): 字符表名称: 我知道fopen方法,但我不确定在这种情况下如何使用它。我希望能够使用此表单创建新网页,并让index.php显示使用上述表单创建的文件列表 使用表单中的值作为文件名,动态更新已创建网页列表并创建这些网页的最佳方法是什么 我还想知道如何修改这些新创建的页面,但我需要先弄清楚这一点 谢谢。请执行以下操作: <?php /
字符表名称:
我知道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(!@fwrite($loHandle, 'Hello World'))
{
echo 'Could not right to file';
}
@fclose($loHandle);
}
?>
<?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);
}
?>
要在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(!@fwrite($loHandle, 'Hello World'))
{
echo 'Could not right to file';
}
@fclose($loHandle);
}
?>
<?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);
}
?>
首先,也是最重要的一点是,在试图管理文件中的数据时,您将遇到可伸缩性/数据损坏问题—这就是数据库的用途 仅使用平面文件存储数据就可以构建大型、快速的系统,但这需要大量复杂的代码来实现复杂的文件锁定队列。但考虑到简单使用数据库的替代方案,这几乎不值得付出努力 允许用户指定文件名意味着他们可以在您的计算机上丢弃任何可由Web服务器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';
}