tags:

views:

50

answers:

1

Hi all

I might be looking at this the wrong way, but I have a form that does its thing (sends emails etc etc) but I also put in some code to make a simple flatfile csv log with some of the user entered details.

If a user accidentally puts in for instance 'himynameis","bob' this would either break the csv row (because the quotes weren't encapsulated) or if I use htmlspecialchars() and stripslashes() on the data, I end up with a ugly data value of 'himynameis","bob'.

My question is, how can I handle the incoming data to cater for '"' being put in the form without breaking my csv file?

this is my code for creating the csv log file.

@$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

Here is a sample of the incoming array data:

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

+1  A: 

You can change any " in user input to "". This is recommended by RFC 4180, and will be handled correctly by OpenOffice Calc and Excel, among other programs.

You can use str_replace for this. It will probably be slightly faster than preg_replace:

function csv_quote_escape($input)
{
  return str_replace('"', '""', $input);
}
Matthew Flaschen
yup, if I encapsulate the double quotes with more doublequotes, the csv is fine (I know that) I'm asking how can I do that. I'm thinking maybe preg_replace, or is there another way??
Jared
legend mate, cheers!
Jared