I am using encodeURIComponent() (and encodeURI() for e-mails) to take inputs safely from the user, and am then sending the output to php via ajax. The php processes it and puts this escaped sting into a $_SESSION[] which I then to to echo later. I was wondering if it was possible to print this to html normally, and then have html ignore anything inside it being code (e.g. would be treated as text instead of a tag) or even combine these two steps. I think the format for JavaScript encoding is different than that of php, so this might be an issue, but if it is, what would be the best way to change these stings in php (I'm storing these escaped strings in MySQL)?
Thanks in advance.
Theese are the functions I use when I handle strings from users in php.
save is for save to database,
edit is editing in input/textareas
show is to write it out showing the tags as text in html.
// SAVE DATA
function save($str)
{
return mysql_real_escape_string($str);
}
//############################################################################
// EDIT DATA
function edit($str)
{
$patterns[0] = '/</';
$patterns[1] = '/>/';
$patterns[2] = '/"/';
$patterns[3] = "/'/";
$replacements[0] = '<';
$replacements[1] = '>';
$replacements[2] = '"';
$replacements[3] = ''';
$str = preg_replace($patterns, $replacements, $str);
$str = trim($str);
return stripslashes(stripslashes(str_replace('\r\n', '
', $str)));
}
//############################################################################
// SHOW DATA
function show($str)
{
$patterns[0] = '/</';
$patterns[1] = '/>/';
$patterns[2] = '/"/';
$patterns[3] = "/'/";
$replacements[0] = '<';
$replacements[1] = '>';
$replacements[2] = '"';
$replacements[3] = ''';
$str = preg_replace($patterns, $replacements, $str);
$str = trim($str);
return stripslashes(stripslashes(str_replace('
', '<br />', $str)));
}
play around with it and see if it works for you :)
Related
Code that works fine except for the issue of passing a value back and forth between JavaScript, Ajax, and PHP. Using TinyMCE as the editor, when I add a paragraph break in the text, save the data (passing it through JavaScript/Ajax and PHP to do so) the text appears to be okay. Here's the JavaScript and Ajax code -- this works, it passes the data correctly to the PHP program when the submit button is clicked:
// save the main who's who form data:
$("form#who_main").submit(function(e)
{
e.preventDefault();
// first thing, clear out the message div used for this (if there's anything there):
document.getElementById("who_message").innerHTML = "";
// because we're using TinyMCE, need to replace value in that into the textarea
// so that when JavaScript gathers the formData it is getting it from the textarea
// controls (it doesn't know what to do with TinyMCE):
var shortbio = tinymce.get('shortbio').getContent();
document.getElementById( "shortbio" ).value = shortbio;
var user_notes = tinymce.get('user_notes').getContent();
document.getElementById( "user_notes" ).value = user_notes;
var admin_notes = tinymce.get('admin_notes').getContent();
document.getElementById( "admin_notes" ).value = admin_notes;
// this loads all the controls of the form rather than doing one at a time and fumbling
// with the file object ...:
var formData = new FormData(this);
// ajax call to attempt to upload and save the image:
$.ajax
({
type: "POST",
url: "<?php echo $History_html_RootPath; ?>admin/AjaxCalls/who_update_main_save.php",
data: formData,
dataType: "json", // return value is json array
processData : false,
contentType: false,
success: function(data)
{
// need to see if we have an error, if so, display it, otherwise,
// we should hopefully have success ...
if ( data[0].toLowerCase().includes( "error" ) )
{
var errormsg = "<div class='alert alert-danger'>"+data+"</div>";
document.getElementById("who_message").innerHTML = errormsg;
return;
}
else
{
// success!
// update things on screen, so we don't get confused using the data array returned
// from PHP:
document.getElementById("namecode").value = data[0];
document.getElementById("region").value = data[1];
document.getElementById("local").value = data[2];
document.getElementById("preferredtitle").value = data[3];
document.getElementById("shortbio").value = data[4];
tinymce.get('shortbio').setContent( data[4] );
document.getElementById("headshotphoto").value = data[5];
document.getElementById("photographername").value = data[6];
document.getElementById("photographerlink").value = data[7];
document.getElementById("user_notes").value = data[8];
tinymce.get('user_notes').setContent( data[8] );
document.getElementById("admin_notes").value = data[9];
tinymce.get('admin_notes').setContent( data[9] );
// clear out the upload file control:
//document.getElementById("headshotphoto").value = "";
// change the message:
var message = "<div class='alert alert-success'>";
message += "<b>Success!</b> This data has been updated in the <i>holding</i> table.";
message += "</div>";
document.getElementById("who_message").innerHTML = message;
return;
}
} // end success
}); // end ajax call
}) // end of code associated with who_main submit
The PHP file receives the data via post, and I use the PHP function mysqli_real_escape_string() to deal with issues. The one problem with doing this is that it appears to insert backslashes for quotes (single and double), and so on. I just had a thought that might be the cause of the problem, and that is the use of this function, I am not sure. I will test it, but in the meantime. ... I save the data to the table and all is good. If there's a paragraph break, the proper tags are saved out into the table.
<p>Some text</p><p>More text 'quoted text'</p>
When I pass the data back using JSON encoding:
$returndata = array();
$returndata[0] = $namecode;
$returndata[1] = $region;
$returndata[2] = $local;
$returndata[3] = $preferredtitle;
$returndata[4] = $shortbio;
$returndata[5] = $photo_file;
$returndata[6] = $photographername;
$returndata[7] = $photographerlink;
$returndata[8] = $user_notes;
$returndata[9] = $admin_notes;
// done-done:
echo json_encode( $returndata );
return;
The code above (the javascript/Ajax code) comes back looking like:
<p>Some text</p>\r\n<p>More text \'quoted text\'</p>
I need to not have the \r\n and \' (or \") showing up in my text. If I were to save it again like that it gets weirder as the backslashes get duplicated and more. I am sure there's some thing I am missing, but I don't know what it is. This is making me crazy because everything else works exactly as I need it to.
NOTE Added code that I have attempted to use, in PHP, to deal with "escapes", it works for single and double quotes, but not for the \r\n characters -- instead it just strips out the backslash:
function remove_escapes( $string )
{
$string = str_replace ( "\'", "'", $string ); // convert single quote
$string = str_replace ( "\"", """, $string ); // convert double-quote
$string = str_replace ( "\r\n", "", $string ); // remove \r\n
$string = str_replace ( "\\", "", $string ); // remove slash
// anything else giving us heartburn?
return $string;
} // eof: remove_escapes()
If I use this with the json array, I get the letters rn inserted between paragraphs:
$returndata[8] = remove_escapes( $user_notes );
$returndata[9] = remove_escapes( $admin_notes );
maybe doing something like data.replace(/\n/g, '<br>') this will replace all newline markers with the html newline or data.replace(/\\n/g, '<br>') to look for the characters rather than a newline marker
I have done some testing to examine the data and it appears to be happening because of the mysqli_real_escape_string() function when I get the data from the $_POST() array. If I take that out, I am not getting the \r\n codes. So perhaps the jquery post is passing things in a way I don't need that function? Further testing on the three different text controls shows it working without the need to use mysqli_real_escape_string, and I have some extra functionality to deal with looking for JavaScript and such in the text, so I may be able to simplify the code. Unless someone can tell me a reason not to do this ...?
The mysqli_real_escape_string() is there so that special characters are escaped, this helps prevent hacking attacks like sql injection.
It appears that the only solution I can find is to continue with mysqli_real_escape_string(), but when passing the information back, after saving the changes, re-load the data from the table, which does not display the escape characters and therefore avoids the issue. It seems like a lot of extra data processing, but it's only ever (in my code) one row at a time that is being passed back and forth.
I want to store html code into sql database which I've encoded by using encodeURI() but it showing me multiple errors as below
I'm using dataType as <CLOB> also tried using NVARCHAR(MAX) but is showing same error.
Sharing my encoded html code below in string format tobe store into sql.
%3Cp%3Ethis%20kind%20of%20text%20i'm%20storing%20into%20database%3C/p%3E%3Cpre%20class=%22code-pre%22%3Evar uri%20= %22my%20test.asp?name=st%C3%A5le&car=saab%22;%0Avar enc%20=%20encodeURI(uri);%0Avar dec%20=%20decodeURI(enc);%0Avar res%20=%20enc%20+ %22<br>%22 +%20dec;%0A%3C/pre%3E
INSERT INTO "Mytable" VALUES(
8/*ID <INTEGER>*/,
'Return matching objects from array of objects'/*QUESTION <NVARCHAR(200)>*/,
'%3Cp%3Ethis%20kind%20of%20text%20i'm%20storing%20into%20database%3C/p%3E%3C pre%20class=%22code-pre%22%3Evar uri%20= %22my%20test.asp ?
name=st%C3%A5le&car=saab%22;%0Avar enc%20=%20encodeURI(uri);%0Avar
dec%20=%20decodeURI(enc);%0Avar res%20=%20enc%20+ %22<br>%22
+%20dec;%0A%3C/pre%3E'/*QUESTION_DESC <CLOB>*/,
'20170508'/*CREATED <TIMESTAMP>*/,
0/*USERID <INTEGER>*/,
1/*TAGID <INTEGER>*/
);
Above command i'm using for pushing data to db. QUESTION_DESC string i've encoded.original string is
<p>this kind of text i'm storing into database</p><pre class="code-
pre">var uri = "my test.asp?name=ståle&car=saab";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
var res = enc + "<br>" + dec;
</pre>
Help will be appriciated
This was quite simple when i tried posting html code from middle ware.
The problem is when i tried to post an html code to database it was showing error because of some random double quotes. So while sending that html code from middle ware i just replaced the double quotes to ignore double quotes. i did like
my html code to be stored in db
var htmlCodeToBeStored =
"<p>this kind of text i'm storing into database</p><pre class="code-
pre">var uri = "my test.asp?name=ståle&car=saab";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
var res = enc + "<br>" + dec;
</pre>"
I replaced above string with as below
htmlCodeToBeStored = htmlCodeToBeStored.replace(/"/g, "\"")
with that simple change i'm able to store my ans into data base.
This is a problem I been having several times, and I always ignore because I cant find a solution.
Basically every time I echoed a value back to Javascript using AJAX, the first value will contain a space (extra character) this is annoying because if I want to check if that value exist sometimes I cant due to the space.
Normally the values returned is something like this
Value1
Value2
Value3
Here is the code below. I suggest to ignore the function seperate_ajx_data as I dont think the problem is located there.
results[0] is giving a white space plus the value!
What could be the issue of having a space in the first value?
PHP code:
$machine = null;
$sql = mysqli_query($connection, "SELECT......");
while($row = mysqli_fetch_array($sql)){
$machine .= $row['MACHINE']."+";
$machine .= $row['COUNT(MACHINE)']."/";
}
echo $machine;
JavaScript code:
function get_machine_vals(id){
var ht = new XMLHttpRequest();
var url = "....";
var val = "....="+id;
ht.open("POST", url, true);
ht.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ht.onreadystatechange = function(){
if(ht.readyState == 4 && ht.status == 200){
var val = ht.responseText;
var results = seperate_ajx_data(["/","+"],val);
var el = document.getElementById("machine_dropdown");
var opts = el.options;
for(var i =0;i<results.length;i++){
var tmp = results[i];
alert(tmp + " " + tmp.length);
switch (results[i]){
case "Test":
opts[0].innerHTML = "Seko "+results[i+1];
break;
}
}
}
};
ht.send(val);
}
function seperate_ajx_data(symbols, val){
var tmp_storage = [];
var tmp_spliter = val.split(symbols[0]);
var results = [];
for(var x = 0;x<tmp_spliter.length;x++){
tmp_storage = tmp_spliter[x].split(symbols[1]);
for(var y = 0;y<tmp_storage.length;y++){
results.push(tmp_storage[y]);
}
}
return results;
}
This is unfortunately one of those "gotchas" when working with PHP. The errant character might come from a space after a closing PHP tag. A contrived example:
<?php
... do some work ...
?> <?php
... do some work, but note errant space between the tags
Possible fixes?
Don't close the PHP tag
Use a different transfer mechanism that is space-tolerant, for example JSON or XML.
Strip (or "trim") your values client side. In context of your code:
var val = (ht.responseText || '').trim();
Just check your opening <?php brackets, there might be a space (i've seen this before).
It happened with me today. And unlike other answers related to opening bracket, for me it was the space after the closing bracket.
<?php
.....
?>[space][space][space]
I removed the spaces. And solved the issue.
i am trying to store some info in my db. One of the fields are Japanese names. I am getting a error:
Warning: #1366 Incorrect string value: '\xE3\x83\xA9\xE3\x83\x87...' for column 'japan-name' at row 1
So i cannot chnage the charset of my db. Can i use PHP or Javascript to convert Japanese/Korean to something else, and them when i go read it, reconvert to Japanese/Korean?
PHP offers the base64_encode() and base64_decode() functions. They are fast, and impose a storage penalty of about 33%. You can use the first to convert your utf-8 east Asian text to what looks like gibberish in ASCII before you store it in your table. The second will convert it back after you retrieve it.
Here's an example:
$jp = " 私はガラスを食べられます。それは私を傷つけません。";
$jpe = base64_encode ($jp);
$jpd = base64_decode ($jpe);
After you run these lines, the $jpe variable has the value
IOengeOBr+OCrOODqeOCueOCkumjn+OBueOCieOCjOOBvuOBmeOAguOBneOCjOOBr+engeOCkuWCt+OBpOOBkeOBvuOBm+OCk+OAgg==
That stores just fine in an ASCII or Latin-1 column.
utf-8 saves the unicode data in table... but other way is to encode and save and then decode and display
update:
searched on web and found answer at How do you Encrypt and Decrypt a PHP String?
define("ENCRYPTION_KEY", "!##$%^&*");
$string = "This is the original data string!";
echo $encrypted = encrypt($string, ENCRYPTION_KEY);
echo "<br />";
echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
/**
* Returns an encrypted & utf8-encoded
*/
function encrypt($pure_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
return $encrypted_string;
}
/**
* Returns decrypted original string
*/
function decrypt($encrypted_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
return $decrypted_string;
}
I simple want to wan to pass php string into java script function here is the code. I know there is problem in sending string to javascript function but how can i solve it????If i pass integer value then it works fine it shows problem
in passing string
echo "<td><a id='".$row['Patient_Id']."' onclick=changename(".$row['Patient_Id'].",".$row['age'].",".$row['Notes'].") >".$row["Patient_Name"]."</a></td></tr>";
Here is the java script funtion
function changename(vlue,age,id)
{
alert(id);
var MyDiv1 = document.getElementById(vlue);
document.getElementById('age').innerHTML=age;
var MyDiv2 = document.getElementById('pname');
MyDiv2.innerHTML = MyDiv1.innerHTML; //d
var MyDiv3 = document.getElementById('hidden');
MyDiv3.value =vlue;
}
Your parameters are string values, so they should be enclosed in quotes:
echo "<td><a id='".$row['Patient_Id']."' onclick=changename( '".$row['Patient_Id']."' , '".$row['age']."' , '".$row['Notes']."' ) >".$row["Patient_Name"]."</a></td></tr>";
// ^----------------------^ etc
As it stands, JavaScript perceives your strings as identifiers. If you had checked your console you'd have seen corresponding errors (assuming these identifiers aren't defined).
your onclick doesn't have quotations
echo "<td><a id='".$row['Patient_Id']."' onclick='changename(".$row['Patient_Id'].",".$row['age'].",".$row['Notes'].")' >".$row["Patient_Name"]."</a></td></tr>";
^ //here ^ // and here