2010-05-16 58 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

相关问题