I can't figure out why my php processing script stops when it encounters a special character in a tinymce textarea.
example if I type foo and submit, fine...no problems but if I type foo<<<, it stops after foo when I submit
the editor is creating the html entities and sending them through ajax
getting the content with
var c = tinyMCE.get('content').getContent();
and sending the content
ajax.send("action=edit_content&c="+c+"&id="+id);
and I can see in firebug that the string is being passed
action=edit_content&c=<p>foo <<<</p>&id=8
and the php is really nothing special at all, just set that post to a var
is it maybe because of the & in the < ? maybe it thinks that is actually another post parameter?
I am still getting my feet wet when it comes to ajax. If I am correct on my assumption, how do I fix that?
You have the right idea. The ampersand is breaking the URL string.
In order to fix breaking characters, you have to escape the string.
Try this:
ajax.send("action=edit_content&c="+escape(c)+"&id="+id);
You probably won't have to (because Apache will do it for you), but if necessary, you can also unescape the string on the PHP side using urldecode:
<?php echo urldecode($_GET['c']); ?>
Related
In an HTML <input>:
Is it an obligation to set name attribute with English characters?
I want to use it later, in $_POST['some_utf8_characters_and_not_english_characters'].
Is it possible to cause a problem later?
According to RFC1866 chapter 3.2.4, an attribute's value can be anything except the value delimiter (single or double quote), and shouldn't contain HTML tag delimiters (< and >).
However, you'll have to test how JavaScript behaves on all browsers (remember your great friend MSIE...) when you try to access a DOM element using name as references. For example: document.anElementWithPersianName or document.forms['aFormWithAPersianName']. So if you use JS to validate, and/or ajax to submit a form, you'll need to be sure that JS is able to handle this character set properly.
In any case, you'll have to ensure that:
your PHP scripts use UTF-8-based functions when it's about string manipulation (I think some functions need to have the charset passed as an argument)
these scripts are themselves saved in UTF-8 files
you correctly set the character set in the HTML header and/or PHP's response header
Best thing to do: create a simple form, do some JS tricks on it, and have a PHP script parse the submitted results and print them.
This is successfully working in one of my websites. No problems.
<input name="UTF_word" />
$_POST['UTF_word']
Both does not give any problems in client side, including jquery (not checked in IE) or server side.
Is there a way to replace the character & with and in a PHP web form as the user types it rather than after submitting the form?
When & is inserted into our database our search engine doesn't interpret the & correctly replacing it with & returning an incorrect search result (i.e. not the result that included &).
Here is the field we would like to run this on:
<input type="text" name="project_title" id="project_title" value="<?php echo $project_title; ?>" size="60" class="btn_input2"/>
Is there a way to replace the character & with and in a PHP web form as the user types it rather than after submitting the form?
PHP is on the server, it has no control over anything taking place under any circumstances what-so-ever on the client-side. It sends raw text from the web server, a 100megaton thermonuclear device explodes, and PHP never exists anymore after the content is sent. Just the document received on your client side remains. To work with effects on your client side, you need to work with JavaScript.
To do that, you would pick your favorite JavaScript library and add an event listener for "keyup" events. Replace ampersands with "and", and drop the replacement text back in the box. mugur has posted an answer that shows you how to do this.
This is a horrible solution in practice because your users will be screaming for bloody justice to deliver them from such an awful user experience. What you've ended up doing is replacing the input text with something they didn't want. Other search tools do this, why can't yours? You hit backspace, then what? When you hit in the text, you probably lose your cursor position.
Not only that, you're treating a symptom rather than the cause. Look at why you're doing this:
The reason is when & is inserted into our database our search engine flips out and replaces it with & which then returns an incorrect result (i.e. not the result that included &).
No, your database and search engine do no such thing as "flipping out". You're not aware of what's going on and try to treat symptoms rather than learn the cause and fix it. Your symptom cure will create MORE issues down the road. Don't do it.
& is an HTML Entity Code. Every "special" charecter has one. This means your database also encodes > as > as well as characters with accents in them (such as French, German, or Spanish texts). You get "Wrong" results for all of these.
You didn't show any code so you don't get any code. But here's what your problem is.
Your code is converting raw text into HTML Entity codes where appropriate, you're searching against a non-encoded string.
Option 1: Fix the cause
Encode your search text with HTML entities so that it matches for all these cases. Match accent charecters with their non-accented cousins so searching for "francais" might return "français".
Option 2: Fix one symptom
Do a string replace for ampersands either on the client or server side, your search breaks for all other encodings. Never find texts such as "Bob > Sally". Never find "français".
Before submitting the form you'd need to use JavaScript to change as the user types it in. Not ideal since JS can be turned off.
You'd be much better to "clean" the ampersands after submitting but before inserting into the database.
A simple str_replace should work:
str_replace(' & ',' and ', $_POST['value']);
But as others have pointed out, this isn't a good solution. The best solution would be to encode the ampersands as they go into the database (which seems to be happening just now), then modify your search script to allow for this.
You can do that as they complete the form with jquery like this:
$('#input').change(function() { // edited conforming Icognito suggestion
var some_val = $('#input').val().replace('&', 'and');
$('#input').val( some_val );
});
EDIT: working example (http://jsfiddle.net/4gXZW/13/)
JS:
$('.target').change(function() {
$('.target').val($('.target').val().replace('&', 'and'));
});
HTML:
<input class="target" type="text" value="Field 1" />
Otherwise you can do that in PHP before the insert sql.
$to_insert = str_replace("&", "and", $_POST['your_variable']);
I think I'm missing something obvious here but it is driving me crazy and I can't figure it out. I'm developing a WordPress plugin and part of it needs to take the WordPress post title and send that to a RESTful web service to do something else. So of course I want to rawurlencode() the post title since who knows what text might be in there. However, for some reason the output I'm getting has extra escape characters and I have no idea where they are coming from (and it's causing problems with the web service I'm calling obviously).
My code is fairly straight forward:
$topic = get_the_title($post_id);
$curl_post_fields = 'name=' . rawurlencode( $topic );
Yet when I print the output of those two strings I get:
topic=a & b
name=a%20%26%23038%3B%20b
Whereas I would expect the URL encoded string to be
name=a%20%26%20b
I have no idea where that extra %23038%3B could be coming from. If I'm reading the encoding on that correctly it translates to #038; but I still don't know where it's coming from.
There seems to be a html encoding in between as well, instead of &, & is in the encoded string. Probably because & has to be escaped in html, and the get_title function escapes this using html_special_chars or something like that.
I had some problems with that when i used an older php version
Annoying brain numbing problem.
I have two functions to check the length of a string (primarily, the js one truncates as well) heres the one in Javascript:
$('textarea#itemdescription').keyup(function() {
var charLength = $(this).val().length;
// Displays count
$('span#charCount').css({'color':'#666'});
$('span#charCount').html(255 - charLength);
if($(this).val().length >= 240){
$('span#charCount').css({'color':'#FF0000'});
}
// Alerts when 250 characters is reached
if($(this).val().length >= 255){
$('span#charCount').css({'color':'#FF0000'});
$('span#charCount').html('<strong>0</strong>');
var text = $('textarea#itemdescription').val().substring(0,255)
$('textarea#itemdescription').val(text);
}
});
And here is my PHP to double check:
if(strlen($_POST["description"])>255){
echo "Description must be less than ".strlen($_POST["description"])." characters";
exit();
}
I'm using jQuery Ajax to post the values from the textarea. However my php validation says the strlen() is longer than my js is essentially saying. So for example if i type a solid string and it says 0 or 3 chars left till 255. I then click save and the php gives me the length as being 261.
Any ideas?
Is it to do with special characters, bit sizes that js reads differently or misses out? Or is it to do with something else? Maybe its ill today!... :P
Update:
I added var_dump($_POST['description'])
to see what was passed and it was returning escape slashes e.g. what\'s going on? I have tried adding stripslashes(); to no avail... where are they coming from?
UPDATE 2 - PROBLEM SOLVED:
Basically I think I just realised my server has magic quotes turned on... grr
So I have stripped slashes before processing now. Bit annoying but it will have to do!!
Thanks for your help!
Thanks,
Stefan
The easiest way to debug this is simply from your PHP script, by using:
var_dump($_POST['description']
I suggest you also use view source in your browser to see any escape code, special char codes, etc...
It would help if you posted more of your front-end code, especially where you are doing the actual POST. That said, are you sure that keyup is called every time? If the user just pastes text into the box have you verified it is still called?
Also keep in mind that JavaScript is not good enough to guarantee that a string will be less than a given length. A user could disable JavaScript, and a savvy "user" can send their own POST request with more than 255 chars.
I suspect that few characters are line breaks (you say you use textarea) that are ignored while you validate using javascript.
I see 2 things that might be causing your problem.
firstly substring(0,255) returns 256 characters
secondly magic_quotes might be turned on in php.ini, PHP tries to give you escaped strings but doesn't do it right all the time
edit
doh didnt re-read the substring definition, ignore the first one but magic_quotes might be on check that one
If you use UTF-8 encoding, PHP strlen() is counting the bytes, not the characters. If you have anything non-ASCII, this will happen. Use mb_strlen(). Magic quotes can add a few characters also.
I have made one form in which there is rich text editor. and i m trying to store the data to database.
now i have mainly two problem..
1) As soon as the string which contents "#"(basically when i try to change the color of the font) character, then it does not store characters after "#". and it also not store "#" character also.
2) although i had tried....in javascript
html.replace("\"","'");
but it does not replace the double quotes to single quotes.
We'll need to see some code. My feeling is you're missing some essential escaping step somewhere. In particular:
As soon as the string which contents "#"(basically when i try to change the color of the font) character
Implies to me that you might be sticking strings together into a URL like this:
var url= '/something.php?content='+html;
Naturally if the html contains a # symbol, you've got problems, because in:
http://www.example.com/something.php?content=<div style="color:#123456">
the # begins a fragment identifier called #123456">, like when you put #section on the end of a URL to go to the anchor called section in the HTML file. Fragment identifiers are purely client-side and are not sent to the server, which would see:
http://www.example.com/something.php?content=<div style="color:
However this is far from the only problem with the above. Space, < and = are simly invalid in URLs, and other characters like & will also mess up parameter parsing. To encode an arbitrary string into a query parameter you must use encodeURIComponent:
var url= '/something.php?content='+encodeURIComponent(html);
which will replace # with %35 and similarly for the other out-of-band characters.
However if this is indeed what you're doing, you should in any case you should not be storing anything to the database in response to a GET request, nor relying on a GET to pass potentially-large content. Use a POST request instead.
It seems that you are doing something very strange with your database code. Can you show the actual code you use for storing the string to database?
# - character is a common way to create a comment. That is everything starting from # to end of line is discarded. However if your code to store to database is correct, that should not matter.
Javascript is not the correct place to handle quote character conversions. The right place for that is on server side.
As you have requested....
I try to replay you... I try to mention exact what I had done...
1) on the client side on the html form page I had written like this..
html = html.trim(); // in html, the data of the rich text editor will come.
document.RTEDemo.action = "submit.php?method='"+ html.replace("\"","'") + "'";
\\ i had done replace bcz i think that was some problem with double quotes.
now on submit.php , my browser url is like this...
http://localhost/nc/submit.php?method='This is very simple recipe.<br><strong style='background-color: #111111; color: #80ff00; font-size: 20px;">To make Bread Buttor you will need</strong><br><br><blockquote><ol><li>bread</li><li>buttor</li></ol></li></blockquote><span style="background-color: #00ff80;">GOOD.</span><br><br><br><blockquote><br></blockquote><br>'
2) on submit.php ........I just write simply this
echo "METHOD : ".$_GET['method'] . "<br><br>";
$method = $_GET['method'];
now my answer of upper part is like this...
METHOD : 'This is very simple recipe.
now i want to store the full detail of URL....but its only storing...
This is very simple recipe.