2010-05-16 104 views
0

我可能會看到這個錯誤的方式,但我有一個窗體,它做的事情(發送電子郵件等等),但我也放了一些代碼來做一個簡單的flatfile csv日誌與一些用戶輸入了詳細信息。如果用戶不小心插入了例如「himynameis」,「bob」這會破壞csv行(因爲引號沒有封裝),或者如果我在數據上使用htmlspecialchars()和stripslashes()我結束了一個醜陋的數據值'himynameis","bob'在數組中包含雙引號

我的問題是,我該怎麼處理傳入的數據,以滿足「'被放置在形式沒有打破我的csv文件?

這是我創建的CSV日誌文件中的代碼。

@$name = htmlspecialchars(trim($_POST['name'])); 
@$emailCheck = htmlspecialchars(trim($_POST['email'])); 
@$title = htmlspecialchars(trim($_POST['title'])); 
@$phone = htmlspecialchars(trim($_POST['phone'])); 


function logFile($logText) 
{ 

    $path = 'D:\logs'; 
    $filename = '\Log-' . date('Ym', time()) . '.csv'; 
    $file = $path . $filename; 

    if(!file_exists($file)) 
    { 
     $logHeader = array('Date', 'IP_Address', 'Title', 'Name', 'Customer_Email', 'Customer_Phone', 'file'); 

     $fp = fopen($file, 'a');   

      fputcsv($fp, $line); 

    } 

    $fp = fopen($file, 'a'); 


    foreach ($logText as $record) { 
    fputcsv($fp, $record); 
} 




} 

//Log submission to file 
     $date = date("Y/m/d H:i:s"); 
     $clientIp = getIpAddress(); //get clients IP address 
     $nameLog = stripslashes($name); 
     $titleLog = stripslashes($title); 

     if($_FILES['uploadedfile']['error'] == 4) $filename = "No file attached."; //check if file uploaded and return 
     $logText = array(array("$date", "$clientIp", "$titleLog", "$nameLog", "$emailCheck", "$phone", "$filename")); 

     logFile($logText); //write form details to log 

這裏是傳入陣列數據的一個示例:

Array 
(
    [0] => Array 
     (
      [0] => 2010/05/17 10:22:27 
      [1] => xxx.xxx.xxx.xxx 
      [2] => title 
      [3] => """"himynameis","bob" 
      [4] => [email protected] 
      [5] => 346346 
      [6] => No file attached. 
     ) 

) 

TIA

Jared

回答

2

您可以將用戶輸入中的任何"更改爲""。這是由RFC 4180推薦的,並且將由OpenOffice Calc和Excel以及其他程序正確處理。

您可以使用str_replace來做到這一點。它可能會比preg_replace函數稍快:

function csv_quote_escape($input) 
{ 
    return str_replace('"', '""', $input); 
} 
+0

燁,如果我與封裝雙引號多雙引號中,CSV是好的(我知道)我問我怎麼能做到這一點。我想也許preg_replace,或者有另一種方式? – Jared 2010-05-16 22:35:55

+0

傳奇伴侶,歡呼聲! – Jared 2010-05-16 23:01:20

相關問題