I am trying to retrieve data from the db in an input field through PHP. Instead of the placeholder, I want to display this retrieved value in the input field if the data exists. I am able to retrieve the data from the db, but it is adding few extra tabs before the actual input.
<input type="text" name="title" id="title" value="
<?php
$title='title';
$clean = trim(retrieve_project_info($email,$title));
echo $clean;
?>">
So, if the input in the db is 'coldplay'. the retrieved data looks like '[tab][tab][tab]coldplay' and the url has many %09s in it.
I have removed whitespaces by using the trim method. But, trim does not remove tabs.
Any idea how to remove these tabs?
Yes, removing tabs is easy, but you better find out why they are there instead of removing them.
But your code:
<input type="text" name="title" id="title" value="
<?php
$title='title';
$clean = trim(retrieve_project_info($email,$title));
echo $clean;
?>">
would be better written like this:
<?php
$title='title';
$clean = trim(retrieve_project_info($email,$title));
?>
<input type="text" name="title" id="title" value="<?php echo $clean; ?>">
Does that help removing your tabs?
The reason I suggest this is because retrieve_project_info could output the tabs.
One more observation: If $clean contains " will your code fail?
EDIT: #palmi
This is how I do it:
function doFormSafeHTMLEncode($someStr){
return htmlspecialchars($someStr,ENT_QUOTES,'UTF-8');
}
And I call that function everywhere where I output raw code to a formfield.
Take out the tabs in your code and put it to the chrome of the screen. I did and it works for me. Even though it is great to have readable code, however this method works for now until i find another solution.
Related
I am working on a school project and am quite new to php so pardon me if this may come off as sounding stupid.
I am trying to use $_GET to fill in a form with the information that was previously inputted into the fields when the user has somehow ran into a problem like leaving fields empty and was forced back into the form web page.
One of the fields may require the user to input operands on mathematical problems (ie. 1+1=2) but when echo-ing back the result the "+" sign is replaced with a space.
<input id="register" name="enun" type="text" class="form-control" placeholder="Question *" value="<?php if(isset($_GET['error'])){echo $_GET['enun'];}?>" />
The link "(...).php?error=equalquestion&enun=1+1=?&resp=2(...)" and I want to echo the bolded part.
I have tried some other fixes around stackoverflow like "htmlentities" / "htmlspecialchars" / "urldecode" but to no avail.
Thank you in advance!
I have a side project that I am working on on learning php and sql, mixed with some ajax. I have the following code(samples) that inserts specific data into a database :
index.php -
<textarea class="form-control txt" rows='3' name="data[Address]" id="Address" placeholder="Your Address">
<?php echo isset($results['data']['Address']) ? str_replace("<br />","\n", $results['data']['Address']): ''; ?></textarea>
functions.php -
$data['data']['Address'] = str_replace("\n","<br />", $data['data']['Address']);
sql data -
if($id!=NULL && !empty($id)){
$query = "UPDATE test SET address = '$data' WHERE id = $id";}
Here is my question. Data saves fine into the database, and I can read it back from index.php, but when I go to RE-save it, it adds whitespace before the address field(3 tabs worth), so that when I go to read the data again through index.php, it does not show.
How can I get it to NOT save whitespace, or to remove unneeded whitespace?
Looks like you're storing the contents from the Textarea as HTML in Database. You should always store the "real data" from your $_POST to database. (So newlines stay newlines in your database). The escaping will happen just before you send the data to the browser using htmlspecialchars() or htmlentities().
For your concrete problem try following: Output your POST form-data directly into your textarea:
<form action="#" method="POST">
<textarea name="input"><?= htmlspecialchars ($_POST["input"]); ?></textarea>
<button name="submit1" type="submit">Send it</button>
</form>
Your input-data should appear as you typed it. So use htmlspecialchars() instead of random trim()'ing or nl2br()'ing.
Additionally: Be carefull when building your SQL-Query. Make sure to proper escape each user-editable variable before adding it to the statement. See: http://php.net/manual/en/mysqli.real-escape-string.php
Do it this way:
mysql_query ("INSERT INTO xyz ('val') VALUE ('" . mysql_real_escape_string($_POST["input"]). "')");
Or - even better: Make yourself familiar with some modern and much more secure way of database accessing - like using PDO ( http://php.net/manual/en/book.pdo.php )
Is there a difference where I place my strip_tags and htmlspecialchars tag's? I read that Example 2 is better than Example 1.
But I don't understand how that can be the case, aren't these the same thing? I don't know if it also makes a difference that I am setting it back into a $_POST[] variable.
In my case, it's much easier to use Example 1, because no matter where I use $_POST['test'], I know it's safe... while I need to find ever instance that I echo $_POST['test'] and put the tags around it for Example 2.
Is one truly version safer against XSS Leaks?
Example 1:
<?php
$_POST['test'] = htmlspecialchars(strip_tags($_POST['test']));
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?=$_POST['test']?>" />
</form>
?>
Example 2:
<?php
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?=htmlspecialchars(strip_tags($_POST['test']))?>" />
</form>
?>
Both examples are equal (in output).
The problem I can see is that example #1 overwrites the $_POST data.
I would advise against doing so because you cannot restore the original data at a later point in the script (e.g. if you wish to save the data into a database or output it in a non-HTML context).
I somehow misunderstood the question, but this part of my old answer is still applicable.
They are two different functions.
In your case you should only use htmlspecialchars() since this function is meant to escape special HTML characters (<, >, ").
strip_tags() on the contrary strips HTML tags (and some other stuff, see the docs). Do you really want this behavior? I doubt that. Stripping HTML tags differs from escaping them insofar that it really removes the tags. Escaping only "escapes" them so that the browser renders them as normal text.
This part of code prevent XSS perfectly.
<?php
$myVar = htmlspecialchars($_POST['test']);
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?php echo $myVar; ?>" />
</form>
?>
I use it like this
$this->message = htmlspecialchars(strip_tags($this->message));
If you have to use $_POST['test'] in multiple spots I would use example 1 since you wont have to process the other functions (strip_tags, htmlspecialchars) over again sanitizing the same data you already have.
I have a page to edit user information, and I wish to show the current information and allow it for editing, to avoid overwriting existing information.
At the moment, I am fetching the data and displaying it in a text area like so:
$usernameQuery = "select username, firstname from USERS where username = '" . $con->escape_string($username) . "'";
$xblah = $con->query($usernameQuery);
while ($row = mysqli_fetch_assoc($xblah))
{
$checkUsername = $row['username'];
$checkFirstName = $row['firstname'];
}
echo "<form name=\"userForm\">
<h1>Editing information for: ".$username."</h1>
<p>
First name:
<textarea rows=\"1\" id=\"firstname\">".$checkFirstName."</textarea>
<br />
</form>"
This text area does not display correctly in firefox, due to a bug of displaying two rows when one is specified. Is there any way to do the same thing with input type=text?
Also, at present, the contents of firstname in the database is john for my testrecord, but var_dump($checkFirstName) shows just s. What must I do to get the actual contents of the field?
Is there any way to do the same thing with input type=text?
<input type="text" name="firstname" value="<?= $checkFirstName ?>" />
As for your other issue, is there another user that has a first name of 's', but also has the same username as the user with the first name of 'john'? The reason I'm saying this is that you use a while loop to fetch your data, so if there are multiple matches, you are going to be left with the last row that matched your query.
Possible ways to resolve this issue include not using a while loop (which implies that you want to fetch/process multiple rows of data) and making sure that all usernames are unique.
Other than that, I don't see why the value fetched from 'firstname' wouldn't match what is in the database.
If you use the input type=text input, anything you put in the value attribute will be shown by default.
echo '<input type="text" value="' . $checkFirstName . '">';
Of course, you'll want to make sure you do some sanitation on $checkFirstName before outputting it into that field, just in case.
As for getting the values of your field, trying var_dumping $row before your while loop, and see if you can figure out what's going wrong with that. If it doesn't show anything helpful, maybe var_dump inside your while loop with a nice < hr > in between each iteration? This should give you a full view of exactly what is being returned in its entirety from your query. Also, if var_dump is a bit too much information for you, check out:
print_r($var)
print_r documentation
Use the 'value' attribute of the input tag.
First name: <input type=\"text\" name=\"name\" value=\"$checkFirstName\"/><br />
textareas are meant to display multiline text with linebreaks. user- and first names are usually not meant to contain those, so better use the input element
<?php
echo '<input type="text" name="name" value="' . htmlentities($checkFirstName) . '">';
?>
don't forget about htmlentities or htmlspecialchars (depends on the encoding - if your encoding is unicode, htmlspecialchars should be sufficient, otherwise its htmlentities). don't use htmlentities just for form fields, but whenever you print user-provided data. otherwise someone could inject xss (cross site scripting) attacks or at least generate faulty html by providing an username like
<script type="text/javascript">execute_evil_code();</script>
as for displaying only one char instead of a full string: normally, this happens if you think you're working with an array and instead have a string. use var_dump($variable); to see the type of your variables.
also, as htw said, check if $username really is unique and you're getting the right row. run the resulting query (echo $usernameQuery;) in phpmyadmin (or whatever tool you're using). if more than one line is returned, your username's not unique (probably a bug in itself) and the row you get is nor the first, but the last one. it's strange, because 's' is not part of "john", so maybe the mysql result set is something completely different. debug at a higher level, and var_dump the whole $row.
Try put all your php code over here:
<textarea id="firstname" rows="1">
<?php
//connect to database
//Select data
if(mysql_num_rows($sql)) {
$row = mysql_fetch_row($sql);
echo nl2br($row['0']);
}
?>
</textarea>
I was going to use jQuery to clone the input field when I click a button to make another field, but I was thinking of doing:
Page One, Page Two, Page Three <- then send that as one $_POST to the server and have it take each page and break on the "," comma then for each insert in to my POSTS table.
Any idea on how I would do that? Would I use explode()? Then inside a foreach() run a query for each item in the field.
So if there were 5 pages typed in separated by commas, it would run five times using the foreach().
for each(){
EXECUTE SQL HERE
}
Does that sound like it would be the best way of going about it?
If you set the name attribute of the input element to the name of an array, e.g. foo[], you'll be able to access it as such when processing the $_POST vars, e.g.
<input name="foo[]" type="text"/>
<input name="foo[]" type="text"/>
becomes two iterations of:
foreach ($_POST['foo'] as $foo) {
// process $foo
}
explode and foreach sound good.
But as Click Upvote indicated: is it for pagination? 'cause then there could be a betetr way to achieve this.
You can do the following:
<input type="text" name="list[]" />
<input type="text" name="list[]" />
<input type="text" name="list[]" />
<input type="text" name="list[]" />
Everytime you need a new input box you can do
$(some_element).append( '<input type="text" name="list[]" />' );
or sth similar with jQuery.
Then you have an array instead of a single value in your PHP $_GET or $_POST variable. So you can use $_POST['list'] in foreach.
I was thinking, I can type in:
Home, Products, About, Contact
Into a input field, then my php can break it apart using the comma and insert each of those page titles in my PAGES table.
Run the SQL within the foreach.
Thoughts?