Trailing spaces when using <textarea> - php

<tr>
<td>
<b>Escalation:
</td></b>
<td>
<TextArea name='escalation' onKeyDown=\"limitText(this.form.escalation,this.form.countdown,100);\"
onKeyUp=\"limitText(this.form.escalation,this.form.countdown,100);\">$Text</textarea>You have <input readonly type=\"text\" name=\"countdown\" size=\"3\" value=\"100\"> characters left.
</td>
</tr>
That is a excerpt of the code im trying to use. Basically I'm trying to fill the text area with a value stored in a php variable, which comes from a SQL database. the Javascript functions limit the amount of text in a block to 100 Chars.
Problem is that it fills whatever space isnt used in the initial value with spaces! I printed the $Text between two quotes so I would know for a fact it doesnt have spaces in the database, which it doesnt. You can also clearly see that I dont have any space at all between the textarea tags so that isnt the issue that I see other posters have.
Any ideas?

Yes, I have seen that behavior before. Check to see if the column that you are reading the value from in the database is of type "CHAR" or type "VARCHAR". It is more efficient to always use fixed-length (CHAR) over variable-length (VARCHAR) field types, so databases are sometimes designed that way. The down side is that shorter data stored in those fields is always padded with spaces.
The solution: You probably have a line in your PHP that looks something like this:
$Text = $row['text'];
Change that line to the following:
$Text = trim($row['text']);
The 'trim' function will strip leading and trailing spaces. If you are using fixed length fields, remember that you will HAVE TO pad the values that you write to the database as well. That means that you will have to add leading spaces to the string to be written to the database to make the then proper length for fixed-width field.

Related

Removing spaces from a selected mysql field using PHP

I need to select a field in mysql and put it in a hidden text field so i can select it into another file. The problem is, the name of the field has spaces in it, so it gets a little buggy. It's something like this:
$GetArea = $_GET['area'];
Then i add this into a hidden textbox:
<INPUT id=txtArea type=hidden value=".$GetArea." name=txtArea />
But it doesn't read the area when i open the site, because the area name is "Area 123" with spaces. This might be a duplicate, but searching around i really couldn't find the answer. Anyone knows of a way to remove the spaces?
To answer your direct queston of how to remove spaces from a variable: Use Regex,
$GetArea = $_GET['area'];
/// = Area 123.
$GetArea = preg_replace("/\s+/","",$_GET['area']);
/// = Area123
View a regex101 example. Regex is far better than using str_replace as in one line it can handle multiple whitespace generating characters (such as the tab character or new line breaker).
However if [in another situation] you want to preserve the spaces and record them you can substitute them for something else such as a _ character:
$GetArea = $_GET['area'];
/// = Area 123.
$GetArea = preg_replace("/\s+/","_",$_GET['area']);
/// = Area_123
The above example means that when you send the data back to the database you can do a preg_replace search and replacement for all _ characters substituted into replace the space character, as needed. (although MySQL only accepts spaces in Column names when properly encased in backticks).
BUT
I would also strongly suggest you get into a habit of encasing your HTML into quotes (single usually) rather than just hanging them out as they are, as this is the principle cause of your issue. so to quote your HTML:
print "<INPUT id='txtArea' type='hidden' value='".$GetArea."' name='txtArea' />";
/** I made an assumption from your syntax your HTML was being printed by PHP **/
This means that you can keep your spaces in your data value of the HTML input element because the whole value section is defined and clearly wrapped in single quote marks.
On a broader note, you really should be looking at not using $_GET and instead transfering data page-to-page with $_POST. Also please research SQL injection and how to prevent it as well as Cross Site Scripting and how to mitigate that. Spaces in MySQL column names is a good habit to avoid.
You should probably use something like this :
$str= str_replace(' ', '', $str);

Php Split text from html text area

I am trying to split a string that i pass from a HTML textarea.
Enter the list of Ids: <textarea rows="4" cols="50" name="ids">
I get it in a php script as
$idlist=$_GET["ids"];
When I try to split it, I couldnt get it with explode. Tried out with multiple delimitiers that could possibly split this and then tried using preg_split. I gave this as my regex.
$ids=preg_split("/\s/",$idlist);
Now that i split, I get empty array elements in the $ids. And I couldnt match them like
$ids[$i]==""|" "|"\s"
1) How will the text in text area be passed? I am giving one Id per line in the text area. It doesnt not carry new line character but a single space.
2) Will preg_split split out even the delimitiers that one uses to split the string?
I know I am making a blunder but couldnt figure out where. Someone any thoughts?
If each ID is on a new line, you need to explode by the new line character \n...
$ids=preg_split("/\r|\n)*/", $idlist);
EDIT: Updated to support windows encoding due to it being sent as a GET not a POST..
Explanation:
Windows send new lines as \r\n so if it is a GET the you need to provide support for this...
Here you go - just using explode to break them down into an array based on the "\n" new line character. I know you mentioned this does not work, but tested it and it works fine for me:
<?php
if (isset($_GET['ids'])) {
$arrayOfIds = explode("\n", $_GET['ids']);
}
?>
<form method="get" action="">
<textarea name="ids"></textarea>
<button type="submit">Submit</button>
</form>
As you mentioned above, when typing ID's into the textarea field I just put them each on a new line.
Figured it out. There was a single space as well as a New line character in the string. Exploded it with \n and then trimmed it with trim() that solved the problem.
With a textarea you have to assume the user is stupid when you ask them to provide data. If you say "Provide an id on each line" assume they will not read it and use commas or assume they press ENTER 50 times at the end, or assume they pasted it in from MS Word. No offense to the user, but just assume they are a Jelly fish on a keyboard and at some point it manages to click "submit".
Taking that into account, (and I'm assuming here that your ids are numbers) it means that anything that isn't a number can be ignored. This makes worrying about new lines, be that \n\r or whatever, completely irrelevant as long as there is some kind of character between each id then that's all we need.
I'm going to change $_GET["ids"] to $_POST["ids"] because I'd be posting that sort of data.
// This will create a list of ids with NO care about what delimeter
// the user used regardless of what you'd requested.
// Replace all non-numeric characters with #
$ids = preg_replace("/[^0-9]/is","#",$_GET["POST"]);
// Remove recursive # and trim
$ids = preg_replace("/#{1,}/is","#",trim($ids,"#"));
// Create array ensuring ids isn't empty
// This also removes unique id entries
$ids = empty($ids)?array():array_unique(explode("#",$ids));
// Show array
echo "<pre>";
print_r($ids);
echo "</pre>";

Copied-and-pasted domain name getting ‎ added to end

When I copy a domain name from Google Maps and then paste it into a form I built, it enters it into a MySQL database with ‎ appended at the end of the domain name.
Any idea how I could strip that ‎ off of the domain name?
The relevant code is below
<div class="friend5title"><label for="url">Website:</label></div>
<div class="friend5field"><input name="website" type="text" id="website" maxlength="150"></div>
$website = mysql_real_escape_string($website);
mysql_query("INSERT INTO submission VALUES ('$website')");
It is a control character ( http://en.wikipedia.org/wiki/Left-to-right_mark ).
Ignore all of my previous answer I just realized (since I wrote quickly) it isn't in unicode it is actually in a HTML entity format so you need to strip that HTML entity out:
preg_replace('/(‎)/', '', $string);
An alternative is to actually purify your string and purge it of all HTML entities since it shouldn't really have any in it. Normally there could be special characters like & but these should not exist in a URL taken from an input field I reckon.
Here is a question about removing HTML entities with a solid answer: How to remove html special chars?
As to why it is happening: it is possible that someone has a foreign browser which artifically makes the text in inputs go a certain way but in turn by adding this html entity.
On pasting in the input field you did copy a left-to-right character, with unicode number 8206. As the browser evidently did have a form not in some unicode character set (like UTF-8), it sent to the server that character as numeric entity ‎. The server has to decode these, or the form (and page) has to be changed to accept UTF-8.
In the case of your LTR-character, it seems superfluous. You could add an onchange=... to remove characters < 0 and > 127 for the URL. They still are characters, so that is easily done.

Certain Characters Deleted When Submitted Through POST

I have two issues
When I submit the character ' through my HTML form (using POST) it is fine. However, in the form I allow to modify the submitted content, when it is brought in, anything after the ' disappears. I've deduced that this is because when I assign the text content containing the ' to the text field, it closes the quote. For example, if I submit Hello there I'm John, it will do: <input type=text value='Hello there I'm Jon />
So you see, the apostrophe in I'm closes the quote for the value attribute. So the only solution I can think of would be to escape the apostrophe, but even when I leave my mysql_real_escape_string() function on the content (as it's submitted to a database escaped and retrieved for this form).
Similarly, when I submit an & or a +, it disappears. This happens any time I try to print it anywhere, regardless of using the htmlspecialchars() function (which I was under the impression should encode them in HTML format for such characters, like: &). so as an example, if someone enters Me & you then it will be displayed as Me you.
So I'm asking: How can I fix the above issues, seeming to have to do with special characters, despite already having them escaped (and I even tried applying the escape function again)? If there is any sample code I should supply, please let me know, but I've explained what I am doing to each input.
When I submit the character ' through my HTML form (using POST) it is fine. However, in the form I allow to modify the submitted content, when it is brought in, anything after the ' disappears. I've deduced that this is because when I assign the text content containing the ' to the text field, it closes the quote. For example, if I submit Hello there I'm John, it will do: <input type=text value='Hello there I'm Jon /> So you see, the apostrophe in I'm closes the quote for the value attribute. So the only solution I can think of would be to escape the apostrophe, but even when I leave my mysql_real_escape_string() function on the content (as it's submitted to a database escaped and retrieved for this form).
This has nothing to do with submitting the data. You are trying to use ' in an attribute value that is delimited with ' characters.
Use htmlspecialchars($data, ENT_QUOTES)
Similarly, when I submit an & or a +, it disappears. This happens any time I try to print it anywhere, regardless of using the htmlspecialchars() function (which I was under the impression should encode them in HTML format for such characters, like: &). so as an example, if someone enters Me & you then it will be displayed as Me you.
In data encoded as application/x-www-form-urlencoded & means "Start of new key=value pair" and + means "A space". You need to urlencode($data).
First, it helps to properly contain HTML attributes, like so:
<input type="text" value="Hello there I'm Jon" />
I'm using double quotes, notice the trailing quote on the value, which your original didn't have. If you then wrap the value in htmlentities() you'll be able to properly display/save " or any other value in your form.
While double quotes aren't strictly necessary in HTML5 (' will work just fine in most cases), they are at least encouraged. If you're using some variant of XHTML, they are required.
A lazy but fast way to do things here is use urlencode() on the contents of the fields before they are posted, and the urldecode() on the other side.
It's not the proper way, or the nice way ... but it works if you don't want to write some specific code to handle the cases.

Actual input contents are not preseving on most of the browsers [FF,MSIE7/8 and etc]

I'm working on one application ( using PHP, javascript ). Below is the short description about my problem statement
There are two forms avaliable on my application, i.e. SourceFrm and targetFrm.
I am taking input on first form i.e. SourceFrm and doing processing on targetFrm.
Below is the input which I am taking from SourceFrm :
1) Enter your data (Identification of this input box id is 'inputdata' ):
2) Enter id ( Identification input box id is id ):
As per above input feed by user I am posting this data to targetFrm for further processiong.
On TargetFrm :
I am simply assigning inputdata value to php varible.
The spaces which are in between of words are getting lost ( more than one spaces converting to one space).
e.g.
User has added below data on input box and submitted
inputdata:
This is my test.
Here observed that user has added 5 spaces in between 'my' and 'test' word.
After assigning this input data to php variable. After that I printed this value
Below content I am getting
Output:
This is my test.
More than one spaces is converting to one space. This behaviour I checked on all browsers like FF,MSIE7/8 opera, safari, chrome.
If have used '<pre>' before printing php variable i.e.:
print "<pre>";
print $inputdata;
At time spaces are not getting lost (I am getting exact content).
Here my conflict is how do I presrve exact contents without using '<pre>'.
I have used encoding/decoding (htmlentitiesencode() and decode () )functionality, in my further data processing, so it may create some conflict if i replace spaces with . ( May conflict ll occur if i use instead space ).
Is anyone has any ideas, suggestions please suggest.
-Thanks
When you output your variables to HTML, they are parsed as HTML. Any additional white space is brought down to one space.
A simple fix would to replace all spaces with the html entitity to force browsers to display each space.
I wouldn't store the string with all the &nbps; in the database, but when you show it the would ensure that each space is seen.
EDIT
I mean only replace spaces on render...like:
print str_replace(' ', ' ', $inputdata);
HTML is capable of showing only one space. I'm not really sure why, but if you check your source code of rendered webpage containing your string, you'll see that it contains all the space, the browser just doesn't show it.
The same is for other space characters, as tabs.
The way to deal with it depends on type of your content. You can either replace spaces with or leave it as it is or do something completely different, i.e. strip more than one space down to one space.
It really depends on naturel of your data–the only real situation, when you would need more spaces than one, that comes to my mind is if you're trying to indent things with spaces, what actually isn't that great idea.
Edit: older resource:
http://www.sightspecific.com/~mosh/WWW_FAQ/nbsp.html

Categories