I am working on a project and a lot of my variables need to contain special characters such as {}[].'"!?/\=+- and many more what is the safest way to pass these variables back and forth between SQL, PHP, and output? and how can I prevent a variable from interfering with my code? Ie:
<?php
echo $var;
echo '$var';
echo "$var";
?>
The best way would be to URL encode your data as soon as it is supplied. Then store it and when you are using it, urldecode it.
Something like
string urlencode ( string $str )
To encode and
string urldecode ( string $str )
To decode. This changes your "special" characters into safe characters.
In PHP, the name of a variable cannot contain special characters (other than the initial dollar sign $ and underscores _). The value of a variable can contain whatever you'd like so long as you follow the rules of defining PHP strings.
The variable values won't interfere with your code. If you're concerned about it interfering with your output HTML, use htmlspecialchars as Rocket Hazmat suggested in the comments.
You can use PDO/MYSQL for isnerting the data into the database..
For converting into html entites you can use htmlchars() function.
An example:
<?php
${'[\*var'} = 1;
echo ${'[\*var'};
https://3v4l.org/5Dr93
Related
I have a php associative array containing strings as values and I encode it to JSON and store it in an html-data attribute. That is read by some JS.
So far so good.
Now, I need to use single quotes for the data attribute, otherwise the context switches.
<section id="settings" data-settings='{"some":"val"}'>
</section>
The question is, can I rely on the json_encode() function of php to encode strings always with double quotes? Surprisingly, I can't seem to find information on this. I only find articles from people having issues with quotes in the array values.
Thanks in advance.
Yes, as defined in the JSON spec, the delimiter will always be ". However, values may contain ' characters, which would break your HTML. To keep it simple and not worry about what might or mightn't pose an issue, HTML-escape your values!
<section data-settings="<?= htmlspecialchars(json_encode($foo)); ?>"></section>
This is guaranteed to work, always, no matter what values you pipe in or how you encode them.
NOTE that htmlspecialchars will by default only encode ", not '; so you must use " as the delimiter in HTML (or change the default escaping behavior).
Double-quotes is just convention - standard in JSON in many languagues. So if you want to store JSON in HTML attribute with double-quotes. You can encode that
In PHP
$encoded_json = base64_encode(json_encode($var));
In HTML
<section id="settings" data-settings='<?=$encoded_json?>'>
In JS
var variable = JSON.parse(atob(encoded_json));
I have this URL parameter:
KKe%7bZoE_%24g)tjm%40
When I put it into a variable and echo it, the result is:
KKe{ZoE_$g)tjm#
How to avoid that?
Data in $_GET is already URL-decoded. If you require the original string, get it from $_SERVER['QUERY_STRING']. Note that you will have to process the query string yourself though, including breaking down the individual components.
Alternatively, use rawurlencode($_GET[..]) to re-encode the value; which may or may not produce slightly differently encoded values than you originally got.
Test it with html_entity_decode - it helpt me a lot with my inputs.
If the string is not shown as it is, you have urlencode() or htmlentities() somewhere in your code. Check that, you shouldn't encode html entities before echoing if you want the string to be intact.
For some reason when preg_replace sees ¬ in string and replaces it with ¬:
$url= "http://something?blah=2&you=3&rate=22¬hing=1";
echo preg_replace("/&rate=[0-9]*/", "", $url) . "<br/>";
But the output is as follows:
http://something?blah=2&you=3¬hing=1 // Current result
http://something?blah=2&you=3¬hing=1 // Expected result
Any ideas why this is happening and how to prevent it?
& has special meaning when used URIs. Your URI contains ¬, which is a valid HTML entity on its own. It's being converted to ¬, hence causing the trouble. Escape them properly as ¬ to avoid this problem. If your data is fetched from elsewhere, you can use htmlspecialchars() to do this automatically.
Use this & in place of this &
because your &no has special meaning
use this url :
http://something?blah=2&you=3&rate=22¬hing=1
and then do your replace accordingly
I have an application that posts content to a MySQL DB via PHP. The PHP uses $_GET to pull the content from the URL and then inserts it into the DB.
This works great, but I have discovered an issue. If the user enters certain characters (", &, and others), the $_GET method does not properly separate the content from the URL.
Let's say the user posts this content:
I love blue & green
In this situation, the & symbol cuts the string after the word blue.
Is there any way for me to edit my PHP file to ignore the & symbol and to actually treat it as part of the variable it is supposed to $_GET? Any help would be great!
You can URLencode data before sending it to the PHP. It's a better solution.
Specials chars must not be used in a query string if those chars are in data.
In Javascript, you can use the escape function : escape(&ee) will give %26ee
The correct method is to urlencode the "&" caracter by the client : pass "%26" instead of "&"
you can use $_SERVER['QUERY_STRING']
from http://php.net/manual/en/reserved.variables.server.php
You could send the request as a base64 encoded string:
$string = base64_encode("This is my long string with &ersands and 'quotes'");
print base64_decode($string);
Note that base64-encoded data takes about 33% more space than the original data.
From the manual:
http://php.net/manual/en/function.base64-encode.php
You also have urlencode
try to urlencode your string:
&
becomes
%26
it's a PHP function :
http://php.net/manual/fr/function.urlencode.php
What about, before creating Query string, encode it ?
$str = "I love blue & green ?=&˙Đ[]";
$str = urlencode($str);
echo $str;
Will return:
I%20love%20blue%20%26%20green%20%3F%3D%26%CB%99%C4%90%5B%5D
You have to URL encode the string before you pass it as a GET parameter. In this particular case you have to replace & symbol with %26.
This can be done for example using javascript right before you send the form.
I need to replace characters in a string with their HTML coding.
Ex. The "quick" brown fox, jumps over the lazy (dog).
I need to replace the quotations with the & quot; and replace the brakets with & #40; and & #41;
I have tried str_replace, but I can only get 1 character to be replaced. Is there a way to replace multiple characters using str_replace? Or is there a better way to do this?
Thanks!
I suggest using the function htmlentities().
Have a look at the Manual.
PHP has a number of functions to deal with this sort of thing:
Firstly, htmlentities() and htmlspecialchars().
But as you already found out, they won't deal with ( and ) characters, because these are not characters that ever need to be rendered as entities in HTML. I guess the question is why you want to convert these specific characters to entities? I can't really see a good reason for doing it.
If you really do need to do it, str_replace() will do multiple string replacements, using arrays in both the search and replace paramters:
$output = str_replace(array('(',')'), array('(',')'), $input);
You can also use the strtr() function in a similar way:
$conversions = array('('=>'(', ')'=>')');
$output = strtr($conversions, $input);
Either of these would do the trick for you. Again, I don't know why you'd want to though, because there's nothing special about ( and ) brackets in this context.
While you're looking into the above, you might also want to look up get_html_translation_table(), which returns an array of entity conversions as used in htmlentities() or htmlspecialchars(), in a format suitable for use with strtr(). You could load that array and add the extra characters to it before running the conversion; this would allow you to convert all normal entity characters as well as the same time.
I would point out that if you serve your page with the UTF8 character set, you won't need to convert any characters to entities (except for the HTML reserved characters <, > and &). This may be an alternative solution for you.
You also asked in a separate comment about converting line feeds. These can be converted with PHP's nl2br() function, but could also be done using str_replace() or strtr(), so could be added to a conversion array with everything else.