Enclose PHP output in quotation marks - php

we have a PHP script that exports orders to .csv files. The system we are exporting too requires each field to be encapsulated in quote marks.
Here is the code where we set each field.
$order_data = array(
'type' => "H",
'order_type' => 'HOME',
'order_date' => $order->order_date,
'account_code' => "REAL",
'document_reference' =>'',
'reference1'=>'',
'reference2'=>'',
'delivery_addess_code'=> '',
'billing_first_name' => $order->billing_first_name ." ".$order->billing_last_name,
'billing_address_1' => $order->billing_address_1 ." ".$order->billing_address_2,
'billing_postcode' => $order->billing_postcode,
'delivery_tel_no'=> $order->billing_phone,
'delivery_contact'=> $order->billing_first_name,
This outputs;
H,HOME,"2015-05-13 13:19:46",REAL,,,,,"Ben Bull","Address 1 Address2",
Some are surround by "" and some aren't how do we get them all to be?

For CSV output, you need to enclose all the values with double quotes. In addition, if the values have double quotes inside them you need to escape those double quotes by using two consecutive double quotes. That's how CSV works.
Check this PHP function below.
function makeCSV($value) {
//Encloses each token (Before and after)
$CSV_TOKEN_ENCLOSER = '"';
//Used to escape the enclosing character if inside the token
$CSV_TOKEN_ENCLOSER_ESCAPER = '""';
//Escape the encloser inside the value
$csv_value = str_replace($CSV_TOKEN_ENCLOSER, $CSV_TOKEN_ENCLOSER_ESCAPER, $value);
//Enclose the value
$csv_value .= $CSV_TOKEN_ENCLOSER . $csv_value . $CSV_TOKEN_ENCLOSER;
//Return
return $csv_value;
}
This does the job as I've explained in the first paragraph. You can use it as such in your case:
$order_data = array(
'type' => makeCSV("H"),
'order_type' => makeCSV('HOME'),
'order_date' => makeCSV($order->order_date),
...
);
However, it looks like you have code that's enclosing the values from your order objects within quotes automatically for you. I suggest you avoid that code, replace that with the usage of the makeCSV function presented above, and then finally just use a standard PHP implode call to get your CSV like this:
$comma_separated_csv = implode(",", $order_data);
Hope this helps.
Cheers.

Try to force all types to string like:
'order_type' => (string) 'HOME'

Related

Write double quotes in square brackets to mySQL

How can I write this into my database field (varchar):
["TEXT"]
I have tried escaping the quotes with backslashes and using double double quotes.
Update
I am using Laravel.
I tried this:
$user = User::create(['email'=> $userEmail,
'name'=> $name,
'customer_id'=> $customer->id,
'things'=> '["TEXT"]'
]);
and this was the result in the db:
"[\"TEXT\"]"
This is how I got I working:
$user = User::create(['email'=> $email,
'name'=> $name,
'email'=> $email,
'customer_id'=> $customer_id,
'things'=> ["TEXT"]
]);
Not really sure what do you mean here.. but simply
INSERT INTO test(varchar_field) VALUES('["TEXT"]'); should help
That's the correct data. When displaying something with double quotes the inner double quotes will need to be escaped with the backslash character. That is:
"[\"TEXT\"]"
Is equivalent to:
'["TEXT"]'
Where no escaping is required because the quotes don't conflict.
This is an artifact of how PHP strings work.
When you test the insertion you should see the result of:
SELECT HEX(things) FROM users WHERE email=?
As showing the actual raw hex data for that column which should be:
5B2254455854225D
Where 5B represents a [ and 5D represents ]. If you're getting 22 at the front and end then for some reason double quotes are actually getting into your column and not just the way PHP displays strings.

Codeigniter insert double quotes

Hi I have a dropdown that needs to be saved in a MYSQL table, and this happens thru this code:
$pjt_table = 'music_fisica';
$full_pjt_save = array(
'physical_format_vinile' => $this->input->post('formato_vinile'),
);
$pjt_save = array(
'user_id' => $this->session->userdata('user_id'),
'id_acquisto' => $this->input->post('id_acquisto'),
'pjt_name' => $this->input->post('pjt_name'),
'pjt_type_name' => $pjt_table,
'pjt_table' => $pjt_table
);
//Full Project
$added_fields = $full_pjt_save+array('last_mod' => time());
$this->db->where('id_acquisto', $this->input->post('id_acquisto'));
//$this->db->set('physical_format_vinile', $this->input->post('formato_vinile'), FALSE);
$save_full_pjt_to_db = $this->db->update('progetti_'.$pjt_table, $added_fields);
$pjt_table_id = $this->db->insert_id();
$this->db->where('id_acquisto', $this->input->post('id_acquisto'));
$this->db->update('progetti', array('distrib_fisica' => '1'));
$exist_pjt = $this->db->get_where('progetti_'.$pjt_table, array('id_acquisto' => $this->input->post('id_acquisto')));
The problem is that the dropdown contains a double quote and get cut off when saved to the table.
And this 45 Giri (7" Singolo, 45 Giri) becomes this 45 Giri (7.
I tried changing the config adding the double quotes
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-\"';
but this doesn't change anything. I tried the XSS filtering false
$config['global_xss_filtering'] = FALSE;
also this doesn't change a thing.
Any suggest?
Search and replace the double quote with " the html equivalent.
Something like:
$yourVariable= str_replace('\"', '"', $yourVariable);
not tested
I solved it, the mistake was in the HTML:
<option value="<?= $value ?>"><?= $value ?></option>
This actually broke the value double quotes due to the item.
Tks everybody.

double quotes in mysql data not working for json

I have code like
$m_strOutput= "{\"success\":true,\"results\":" . $m_objQuery->num_rows() . ",\"rows\":";
$m_strOutput = $m_strOutput . json_encode($m_objQuery->result());
$m_strOutput = $m_strOutput . "}";
But some data already has double quotes in it. So it breaks my views where i try to parse it. How do i solve this double quotes problem.
Two things:
This is not a problem of double quote. You'll have syntax error to put a value into a JSON object without a key.
You should let json_encode do all the jobs for you.
Codes that might fit your case:
<?php
$m_strArr = array(
'success' => true,
'results' => $m_objQuery->num_rows(),
'rows' => $m_objQuery->result(),
);
$m_strOutput = json_encode($m_strArr);
?>

PHP making an URL link work inserting the $variables the right syntax way

I have this link that works.
echo '<a href="?country=Estonia&from_language=Russian&into_language=Latvian&submitted=true&
page='.$x. '">'.$x.'</a> ';
But I need the nouns Estonia, Russian and Latvian replaced by scalar variables like $country, $from_language, $into_language.
I have tried all possible combinations of dots and single and double quotes. I always get syntax errors. I don't know how the embed the variables there.
Anybody knows?
thank you
Do yourself a massive favour and use http_build_queryDocs:
<a href="?<?php echo http_build_query(array(
'country' => $country,
'fromLanguage' => $fromLanguage,
'somethingElse' => $somethingElse,
'...' => '...'
), '', '&'); ?>">Link</a>
use something easy one like sprintf or printf.
eg:
printf('<a href="?country=%s&from_language=%s&into_language=%s&submitted=true&
page=%s">%s</a>', $country, $fromLanguage, $toLanguage, $pageID, $dispText);
You could also use something like encoding with double quote sign like:
echo "<a href=\"?country={$country}&from_language={$fromLanguage}&into_language={$toLanguage}&submitted=true&
page={$pageID}\">{$dispText}</a>"
Avoid to put variables directly into string when not extremely simple. Use concatenation instead, and escape string if you want to make something good:
echo '<a href="?country=' . htmlentities($country) .
'&from_language=' . htmlentities($from_language) .
'&into_language=' . htmlentities($into_language) .
'&submitted=true&page=' . intval($x) . '">' . htmlentities($x) . '</a> ';
Anyway, if you really want it the complex way, you have to consider that you need doble quotes for HTML attributes, but double quotes are needed to wrap the PHP string because you want to put variables in it. So, you must escape HTML double quotes. Try:
echo "' . $x . ' ';
Combining the answers of Corbin and KoolKabin gives you this easy-to-read snippet:
printf('%s',
htmlspecialchars(
http_build_query(array(
'country' => $country,
'from_language' => $from_language,
'into_language' => $into_language,
'submitted' => 'true',
'page' => $x
))
),
htmlspecialchars($x));
Parametrization
printf and sprintf are very useful for adding parameters to strings. They make it easy to add escaping or complex values without making the string itself unreadable. You can always see at a glance what string it is by the first parameter.
http_build_query is also a way of parametrizing, but for the querystring. The main use is that you don't need to focus on the syntax of querystrings at all.
Escaping
htmlspecialchars makes sure that the data is fit for insertion into HTML code. It's similar to escaping in SQL queries to avoid SQL injections, only here we want to avoid HTML injections (also called XSS or cross-site scripting).
http_build_query will automatically make sure that all values are escaped for insertion as an URL in the address field in a browser. This does not guarantee fitness for insertion into HTML code. htmlspecialchars is therefore needed for the querystring as well!
If you scripts output HTML, consider to configure the output setting for argument separators arg_separator.output:
ini_set('arg_separator.output', '&');
You can then simply create the URI query info path by using http_build_query:
$country = 'de';
$fromLanguage = 'en_EN';
?>
Link
Which will give you a perfectly validly encoded output, which is immune to injections:
Link
Full Demo
$country = 'Estonia';
$from_language = 'Russian';
$into_language = 'Latvian';
echo ''.$x.' ';
OR
echo "$x";
OR
echo "{$x}";

How to str_replace a section of PHP Code

$embedCode = <<<EOF
getApplicationContent('video','player',array('id' => $iFileId, 'user' => $this->iViewer, 'password' => clear_xss($_COOKIE['memberPassword'])),true)
EOF;
$name = str_replace($embedCode,"test",$content);
I'm trying to replace a section of code with another piece of code. I can do it with smaller strings but once I added the larger strings to $embedCode, it throw an "unexpected T_ENCAPSED_AND_WHITESPACE" error
you should unescape the $ using \$
$embedCode = <<<EOF
getApplicationContent('video','player',array('id' => \$iFileId, 'user' => \$this->iViewer, 'password' => clear_xss(\$_COOKIE['memberPassword'])),true)
EOF;
IF your objective is to use the vars name, if you want to use the real value of the variables, then the problem is in $this->iViewer...
remove ' around the memberPassword near the $_COOKIE
anyway seems you're looking for language construction that not interprets variable inside - so then you have to use not HEREDOC syntax - but regular string definition limited with '
$sample = 'qwe $asd zxc';
or escape $ with \ as Marcx propose below

Categories