2012-03-29 158 views
0

我正在試圖製作一個網站,它將動態地保存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顯示使用上述表單創建的文件列表。

什麼是動態更新已創建網頁列表並創建這些網頁的最佳方式,使用表單中的值作爲文件名。

我也想知道如何改變這些新創建的頁面,但我需要先弄清楚這一點。

謝謝。

回答

0

執行以下操作:

<?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); 
    } 
?> 
0

這裏的第一個,也是最重要的一點是,你會遇到試圖管理文件中數據的可伸縮性/數據損壞問題 - 這就是數據庫的用途。

僅使用平面文件來存儲數據就可以構建大型,快速的系統,但這需要大量複雜的代碼來實現複雜的文件鎖定隊列。但是考慮到簡單地使用數據庫的替代方案,很少值得付出努力。

允許用戶指定文件名意味着他們將能夠清除您的機器上的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'; 

}