I saved some data in the database using mysql_real_escape_string() so the single quotes are escaped like this '. It looks ok in the browser, but how can I convert it back to single quote when I save the text in a txt file?
Please note that mysql_real_escape_string() does not turn apostrophes ' into ' Only HTML-oriented functions do, so you must have calls to htmlentities() somewhere in your script.
As for your question, the function you're looking for is html_entity_decode()
echo html_entity_decode(''', ENT_QUOTES);
This is the reason why you should not store encoded text in the database. You should have stored it in it's original format, and encoded it when you display it.
Now you have to check what characters the function does encode, and write string replacements that converts them back, in reverse order.
Pseudo-code example:
s = Replace(s, "'", "'")
s = Replace(s, "<", "<")
s = Replace(s, ">", ">")
s = Replace(s, "&", "&")
That is just an ascii value of "'", use chr to get it back to a character. Here's the code
$string = "Hello ' Man";
$string = preg_replace('|&#(\d{1,3});|e', 'chr(\1)', $string);
echo $string; # Hello ' Man
Related
I'm using this simple code to transform database query results into JSON format:
$result = $mysqli->query("
SELECT
date as a
, sum(sales) as b
, product as c
FROM
default_dataset
GROUP BY
date
, product
ORDER BY
date
");
$data = $result->fetch_all(MYSQLI_ASSOC);
echo stripslashes(json_encode($data));
The problem is that if there are double quotes in the data (e.g. in the product column) returned by this query. The json_encode function does not encode the data in a good JSON format.
Could someone help me how to escape the double quotes that are returned by the query? Thank you.
You will need htmlspecialchars instead of stripslashes with proper encoding (UTF-8, if your page uses UTF-8 charset) and ENT_QUOTES which will escape double quotes preventing data to break. See the code below:
echo htmlspecialchars(json_encode($data), ENT_QUOTES, 'UTF-8');
json_encode already takes care of this, you are breaking the result by calling stripslashes:
echo json_encode($data); //properly formed json
Example with a simple array with double quotes string value.
$yourArr = array(
'title' => 'This is an example with "double quote" check it'
);
// add htmlspecialchars as UTF-8 after encoded
$encodeData = htmlspecialchars(json_encode($yourArr), ENT_QUOTES, 'UTF-8');
echo $encodeData;
Result:
{"title":"This is an example with \"double quote\" check it"}
According to PHP Manual:
That said, quotes " will produce invalid JSON, but this is only an
issue if you're using json_encode() and just expect PHP to magically
escape your quotes. You need to do the escaping yourself.
Yes, PHP json_encode wouldn't "escape double" quotes, we need to escape those manually in this super simple way-
array_walk($assoc_array, function(&$v, $k) {
if(is_string($v) && strpos($v, '"') !== false) {
$v = str_replace('"', '\"', $v);
}
});
// After escaping those '"', you can simply use json_enocde then.
$json_data = json_encode($assoc_array);
to encode the quotes using htmlspecialchars:
$json_array = array(
'title' => 'Example string\'s with "special" characters'
);
$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');
You can done that using base64_encode and base64_decode
To store in database first convert it to base64_encode and stored into database and if you want that data then you can decrypt that data using base64_decode
$var['cont'] = base64_encode($_POST['data']);
$dd = json_encode($var['cont']);
echo base64_decode ( json_decode($dd) );
$varHi I know this is an extremely basic task, but I am some what confused.
I am pulling a String back from a Database and assigning it to $var. I am then outputting this value into a text area. However, when I do, the string is surrounded in " ".
e.g. "This is the String", but I just want : This is the String
I have tried many functions. I am using chr(34) to search for the ", but to no avail. It will only replace them if it is inside the string. Not on the outside / surrounding the string.
$var = str_replace( chr(34), "" ,$var);
Thanks In Advance for any help.
EDIT : Turn's out I was outputting incorrectly into the text area
""
should have been
Thank's for the help.
$var = str_replace( '"', '' ,$var);
See it in action here
$var = str_replace('"', '', $var);
What about $var = str_replace('"', '', $var);?
you could use str_replace, as already mentioned but that would remove quotes from the string body also (if you have any)
to remove only the first and last ones you could use the trim function with the optional second parameter
edit: and if you have quotes inside the string that you want to keep those might be escaped so you might use str_replace to use only the quotes instead the escaped quotes ( str_replace('\"', '"', $string) );
The double speech should only appear if they are in your data being pulled, unless you are echoing or printing to the text area incorectly.
As said above the
$var = str_replace('"', '', $var);
Will work fine, but its a bit of a hack if your data doesn't have the double speech in it to start with.
<?php
include 'db_connect.php';
$q = mysql_real_escape_string($_GET['q']);
$arr = explode('+', $q);
foreach($arr as $ing)
{
echo $ing;
echo "<br/>";
}
mysql_close($db);
?>
Calling:
findByIncredients.php?q=Hans+Wurst+Wurstel
Source code HTML:
Hans Wurst Wurstel<br/>
Why is there only one newline?
+s in URL are urlencoded spaces. So what php sees in the variable is "Hans Wurst Wurstel". You need to split by space ' ', not +
arr = explode (' ',$q);
"+" gets converted to SPACE on URL decoding.
You may want to pass your string as str1-str2-str3 in get parameter.
Try:
<?php
include 'db_connect.php';
$q = mysql_real_escape_string($_GET['q']);
$arr = explode (' ',$q);
foreach($arr as $ing)
{
echo $ing;
echo "<br/>";
}
mysql_close($db);
?>
Hans+Wurst+Wurstel is the url escaped query string. The php page will likely process it once unescaped (in this case, all +s will be translated into spaces). You should choose a delimiter for explode according to the string as it is in that moment. You can use print_r() for a raw print if you don't know how the string (or any kind of variable) looks like.
Easy. While the standard RFC 3986 url encoding would encode the space " " as "%20", due to historical reasons, it can also be encoded as "+". When PHP parses the query string, it will convert the "+" character to a space.
This is also illustrated by the existence of both:
urlencode: equivalent of what PHP uses internally, will convert " " to "+".
rawurlencode: RFC-conformant encoder, will convert " " to "%20".
I'm assuming you want to explode by space. If you really wanted to encode a "+" character, you could use "%2B", which is the rawurlencode version and will always work.
(EDIT)
Related questions:
When to encode space to plus (+) or %20?
PHP - Plus sign with GET query
I am writing some JavaScript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?
<script type="text/javascript">
$('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
Quite simply: echo str_replace('\'', '\\\'', $myString);
However, I'd suggest use of JSON and json_encode() function as it will be more reliable (quotes new lines for instance):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
If you want to escape characters with a \, you have addcslashes(). For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape ', ", \, and nul (the byte null), you can use addslashes():
echo addslashes($value);
str_replace("'", "\'", $mystringWithSingleQuotes);
In some cases, I just convert it into ENTITIES:
// i.e., $x= ABC\DEFGH'IJKL
$x = str_ireplace("'", "'", $x);
$x = str_ireplace("\\", "\", $x);
$x = str_ireplace('"', """, $x);
On the HTML page, the visual output is the same:
ABC\DEFGH'IJKL
However, it is sanitized in source.
Use the native function htmlspecialchars. It will escape from all special character. If you want to escape from a quote specifically, use with ENT_COMPAT or ENT_QUOTES. Here is the example:
$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
The output would be like this:
Jane & 'Tarzan'<br>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'
Read more in PHP htmlspecialchars() Function
To replace only single quotes, use this simple statement:
$string = str_replace("'", "\\'", $string);
You can use the addcslashes function to get this done like so:
echo addcslashes($text, "'\\");
After a long time fighting with this problem, I think I have found a better solution.
The combination of two functions makes it possible to escape a string to use as HTML.
One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.
Solution:
mysql_real_escape_string(htmlspecialchars($string))
Solve:
a PHP line created to call a JavaScript function like
echo
'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"
I wrote the following function. It replaces the following:
Single quote ['] with a slash and a single quote [\'].
Backslash [\] with two backslashes [\\]
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\'
);
return strtr($target, $replacements);
}
You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".
/**
* With new line replacements too
*/
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\',
"\r\n" => "\\r\\n",
"\n" => "\\n"
);
return strtr($target, $replacements);
}
The neat feature about strtr is that it will prefer long replacements.
Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.
Here is how I did it. Silly, but simple.
$singlequote = "'";
$picturefile = getProductPicture($id);
echo showPicture('.$singlequote.$picturefile.$singlequote.');
I was working on outputting HTML that called JavaScript code to show a picture...
I am not sure what exactly you are doing with your data, but you could always try:
$string = str_replace("'", "%27", $string);
I use this whenever strings are sent to a database for storage.
%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.
To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.
Happy injection avoiding!
I am building a XML RSS for my page. And running into this error:
error on line 39 at column 46: xmlParseEntityRef: no name
Apparently this is because I cant have & in XML... Which I do in my last field row...
What is the best way to clean all my $row['field']'s in PHP so that &'s turn into &
Use htmlspecialchars to encode just the HTML special characters &, <, >, " and optionally ' (see second parameter $quote_style).
It's called htmlentities() and html_entity_decode()
Really should look in the dom xml functions in php. Its a bit of work to figure out, but you avoid problems like this.
Convert Reserved XML characters to Entities
function xml_convert($str, $protect_all = FALSE)
{
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// ampersands won't get messed up
$str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
if ($protect_all === TRUE)
{
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
}
$str = str_replace(array("&","<",">","\"", "'", "-"),
array("&", "<", ">", """, "'", "-"),
$str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
if ($protect_all === TRUE)
{
$str = preg_replace("/$temp(\w+);/","&\\1;", $str);
}
return $str;
}
Use
html_entity_decode($row['field']);
This will take and revert back to the & from & also if you have &npsb; it will change that to a space.
http://us.php.net/html_entity_decode
Cheers