2010-01-01 60 views
1

的名字我目前有:PHP的fopen - 文件

<?php 
    if (isset($_POST["submitwrite"])) { 
     $handle = fopen("writetest.txt","w+"); 
     if ($handle) { 
      fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time()); 
      fclose($handle); 
     } 
    } 
?> 

不過,我需要調整的文件名是動態的,而不是「writetest.txt」我想它是:用戶名+ pollname +時間.txt取$ _post變量。

我也想改變這些文件存儲到/結果的目錄。

請幫助...

+1

那麼問題是什麼? – notnoop 2010-01-01 21:29:11

回答

1

你的意思是做這樣的事情?

$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt'; 
if (isset($_POST["submitwrite"])) { 
    $handle = fopen($filename,"w+"); 
    // etc... 

還是我不理解你?

編輯
爲了解決BalusC指出的問題,這是一個比較完整的解決方案。
它確保$_POST['username']$_POST['pollname']值有效,因此它們不會創建無效或可能有害的$filename

<?php 
$basedir = '/results'; 
$basename = 'time.txt'; 

// Get user and poll names 
$username = $_POST['username']; 
$pollname = $_POST['pollname']; 

// Counteract the old magic_qutoes feature, if needed. 
if(get_magic_quotes_gpc()) { 
    $username = stripslashes($username); 
    $pollname = stripslashes($pollname); 
} 

// Validate user and poll names. 
$regexp = '/^[\w\d\_\-\. \']+$/iu'; 
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) { 
    echo 'Username or pollname is invalid. Aborting!'; 
} 
else { 
    // Compile the complete file name 
    $filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename; 

    // Write to the file 
    if (isset($_POST["submitwrite"])) { 
     $handle = fopen($filename,"w+"); 
     if ($handle) { 
      fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time()); 
      fclose($handle); 
     } 
    } 
} 
?> 
+0

Perfecto!一些你如何理解我...... – CLiown 2010-01-01 21:46:19

+0

如果有一個用戶名爲「foo /../bar」的用戶會怎麼樣? – BalusC 2010-01-01 21:48:21

+0

@BalusC:只允許a-z,0-9和_和 - 用戶名? – Midas 2010-01-01 21:53:58

1

創建的fopen(至少嘗試)的文件,如果它不存在,所以 $文件名= $的用戶名。 $ pollname。 $時間。 '。文本'; $ handle = fopen($ filename,'w +');

會正常工作。 順便說一下,w +將指針放在文件的開頭。如果文件已經有一些數據,它會首先截斷它。如果你想追加數據到文件,你可能想使用'a +'