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.
Related
Within the array that I retrieve from mysql is a text field that contains an ellipsis as part of the entry. While mysqli will print out the array record properly, when I try to encode it to a json string (json_encode), I get an error...actually nothing happens. At this point I know enough about json to be dangerous. Hopefully somebody has an answer to this. In the meantime I found the offending records and have changed the ellipsis (...) to colon-minus (:-) which seems to work. For presentation sake, I'd like to include the ellipsis.
Thanks,
KCT3937
"At this point I know enough about json to be dangerous." as well so my suggestion is to work around the problem if you can't find a "proper" solution.
Replace the offending character with something else before encoding and replace it back to the ellipsis in the JavaScript that receives the response.
If you are using php you may also want to look into JSON_UNESCAPED_UNICODE. Check the json_encode online manual for more details.
Another thing to check is verify that your data is UTF-8 encoded.
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']); ?>
my code is not working ? and i dont want to use str_replace , for there maybe more slashes than 3 to be replaced. how can i do the job using preg_replace?
my code here like this:
<?php
$str='<li>
<span class=\"highlight\">Color</span>
Can\\\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
$str=preg_replace("#\\+#","\\",$str);
echo $str;
There is merit in the other answers, but to me it looks like what you're actually trying to accomplish is something very different. In the php code \\\' is not three slashes followed by an apostrophe, it's one escaped slash followed by an escaped apostrophe, and in the rendered output, that's exactly what you see—a slash followed by an apostrophe (with no need to escape them in the rendered html). It's important to realize that the escape character is not actually part of the string; it's merely a way to help you represent a character that normally has very different meaning in within php—in this case, an apostrophe normally terminates a string literal. What looks like 4 characters in php is actually only 2 characters in the string.
If this is the extent of your code, there's no need for string manipulation or regular expressions. What you actually need is just this:
<?php
$str='<li>
<span class="highlight">Color</span>
Can\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
echo $str;
?>
Only one escape character is needed here for the apostrophe, and in the rendered HTML you will see no slashes at all.
Further Reading:
Escape sequences
The root of this problem is actually in how it was written into your database and likely to be caused by magic_quotes_gpc; this was used in older versions and a really bad idea.
The best fix
This requires a few steps:
Fix the script that puts the HTML inside your database by disabling magic_quotes_gpc.
Write a script that reads all existing database entries, applies stripslashes() and saves the changes.
Fix the presentation part (though, that may need no changes at all.
Alternative patch
Use stripslashes() before you present the HTML.
use this pattern
preg_replace('#\\+#', '\\', $text);
This replaces two or more \ symbols preceding an ' symbol with \'
$theConvertedString = preg_replace("/\\{2,}'/", "\'", $theSourceString);
Ideally, you shouldn't have code causing this issue in the first place so I would have a look at why you have \\' in your code to begin with. If you've manually put it in your variables, take it out. Often, this also happens with multiple calls to addslashes() or mysql_real_escape_string() or a cheap hosting providers' automatic transformation of all POST request variables to escape slashes, combined with your server side PHP code to do the same.
I wrote a script that when you enter a textbox, it will open an invisible iframe to a .php file with $_GET of what they wrote into the textbox.
However, for example, if I type: '<3' in it, this is what happens.
PHP determins that the $_GET[s] is blank! Users cant put a simple <3 symbol without getting that error.
Another problem is quotes, if I write any quotes, it will end the entire SRC property.
What should I do? Should I do something with javascript, or even PHP? Please let me know!
Thanks!
Use urlencode to encode the inputted string into a valid one for URL use.
Also be very cautious when allowing user input into your PHP script through the URL. Make sure you do proper checks/sanitization, especially if database operations are involved.
It looks like your iframe is generated by JavaScript, so all those answers that include PHP functions are useless. The data isn't even reaching PHP, so how can any PHP function hope to help?
Instead, try using urlencode from PHPJS, since none of JS's functions really handle all cases well, and this makes it easy for you to use PHP's urldecode to retrieve the data.
You need to encode that character as <.
Regarding double quotes, you can use this trick.
attr='Your string can "contain double quotes"'
or
attr="Your string can 'contain double quotes'"
but while specifying variable=values in url, you don't need to user double quotes, you can directly assign the values.
like
url="test.php?var1=123&var2=345"
rest about sending the <3 characters, you can check for url encoding in javascript & PHP whichever applicable!
I've asked this question before but I didn't seem to get the right answer. I've got a problem with new lines in text. Javascript and jQuery don't like things like this:
alert('text
text);
When I pull information from a database table that has a break line in it, JS and jQuery can't parse it correctly. I've been told to use n2lbr(), but that doesn't work when someone uses 'shift+enter' or 'enter' when typing text into a message (which is where I get this problem). I still end up with separate lines when using it. It seems to correctly apply the BR tag after the line break, but it still leaves the break there.
Can anyone provide some help here? I get the message data with jQuery and send it off to PHP file to storage, so I'd like to fix the problem there.
This wouldn't be a problem normally, but I want to pull all of a users messages when they first load up their inbox and then display it to them via jQuery when they select a certain message.
You could use a regexp to replace newlines with spaces:
alert('<?php preg_replace("/[\n\r\f]+/m","<br />", $text); ?>');
The m modifier will match across newlines, which in this case I think is important.
edit: sorry, didn't realise you actually wanted <br /> elements, not spaces. updated answer accordingly.
edit2: like #LainIwakura, I made a mistake in my regexp, partly due to the previous edit. my new regexp only replaces CR/NL/LF characters, not any whitespace character (\s). note there are a bunch of unicode linebreak characters that i haven't acknowledged... if you need to deal with these, you might want to read up on the regexp syntax for unicode
Edit: Okay after much tripping over myself I believe you want this:
$str = preg_replace('/\n+/', '<br />', $str);
And with that I'm going to bed...too late to be answering questions.
I usually use json_encode() to format string for use in JavaScript, as it does everything that's necessary for making JS-valid value.