Probably, this question has been asked before, though, I'll ask it again.
Currently, I'm facing a problem with form encoding. When posting my form, all spaces are replaced by the "+" character. I would like to replace this "+" character by a real space.
Does someone has a PHP solution for this?
Thanks in advance.
Cheers, Lennart
Can't reproduce
<form>
<input type=text name="a" value="text with spaces">
<input type=submit>
</form>
<?php if (isset($_GET['a'])) echo $_GET['a'] ?>
no spaces at all. What i m doing wrong?
This shouldn't happen if the browser behaves correctly. My assumption would be that a javascript is messing with your data. Replacing spaces with pluses is done when encoding urls, maybe that will help.
You can use firebug to check for any js interference.
I'm using AJAX (x = in this case JSON) for handling the form posts etc
Then let's see the code.
Possibly you're doing something like trying to form-encode your data manually before another component also form-encodes it. Replacing a space with + is quite standard and expected for form-encoding, but if you accidentally do it twice then you're going to be left with an encoded + at the end of it.
If you are using the JavaScript escape function: don't. (When you need to URL-encode a form value for inclusion in a parameter, the proper method is encodeURIComponent. escape is a fruity non-standard encoding of its own which you should almost never have any need to use.)
Related
I'm trying to output the name of a project i.e. "David's Project" in a form, if a user does not correctly input all data in the form, to save the user having to input the name again.
If I var_dump $name I see David's project. But if I echo $name I see David"'" Project. I realise that ' (single quote) becomes "'"; but I have tried using ENT_NOQUOTES and ENT_COMPAT to avoid encoding the single quote but neither works.
$name = trim(filter_input(INPUT_POST, 'name0', FILTER_SANITIZE_STRING));
<form method="post" class="form" />
Title: <input type="text" name="name0" value="<?php echo
htmlspecialchars($name, ENT_NOQUOTES); ?>">
Am I doing something wrong or should the ENT_NOQUOTES work? I tried using str_replace to replace with ' with an \' but this didn't work either.
The only way round this I have found is to use this:
htmlspecialchars_decode(htmlspecialchars($name, ENT_NOQUOTES));
Is that acceptable?
Sorry I realise this is probably a really stupid question but I just can't get my head around it.
Thanks for any replies.
You can accept a simple answer if it solves your problem BUT you should really understand that what you have delved into is a much larger issue you or someone has created for you.
Databases should not contain HTML encoded characters unless they are specifically meant for storing HTML. I highly doubt this is the case as it very rarely is.
Someone is inserting HTML into your database (html encoding data on insert). This means if you ever want to use a mobile app that is not HTML based, or a command line, or anything at all that might use the data and isn't HTML based, you are going to run into a weird problem where the HTML encoded characters have to be removed on output. This is typically kind of the backwards way to do it and can often cause issues.
You rarely need to "sanitize" your inputs. If anything, you should reject input that is not allowed OR simply escape it in the proper way while inserting it into the database. Sanitizing is only a thing in very special circumstances, which you don't appear to have right now. You're simply inputting and outputting text.
You should pretty much never change users input
My suggestion, if possible, is to fix your INSERT code first so it isn't html encoding data. This html encoding should happen when you output the data TO AN HTML FORMAT. You would use htmlspecialchars() to do this.
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!
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']);
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.
Just getting into PHP web development. I've got an HTML form where a user checks some series of dynamically-generated checkboxes, and submits via POST. On the PHP side, I want to check which of the check-boxes were clicked.
I have an array $full_list, and am doing something like
$selected_checkboxes = array_filter($full_list, function($item) {
array_key_exists($item, $_POST);
}
I run into problems when a list item is named, for example "Peanut Butter", since in the POST array it is named "Peanut_Butter".
I could certainly just str_replace " " with "_" before checking array_key_exists, but I imagine that there is a more fundamental encoding problem here; specifically, I'm not sure of exactly what layer transforms normal strings in HTML Forms (value="Peanut Butter") into "Peanut_Butter".
So:
what layer is responsible for this conversion? Is it the browser?
what are the exact conversion rules, and is there a PHP function out there that will replicate that exact conversion?
The accepted answer by Byron Whitlock is wrong. PHP is indeed the culprit here. See the PHP manual:
Dots and spaces in variable names are converted to underscores. For
example <input name="a.b" /> becomes $_REQUEST["a_b"].
Also refer to the answers of this similar question.
PHP doesn't do this. There is something on the client side that is converting spaces to underscores.
The browser should encode each variable using the equivalent of urlencode(). PHP will automatically decode these strings so it is transparent for the programmer.
edit
The equivalent in javaScript is escape(). But it is very very likely there is some js code manually converting spaces to underscores.