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>
Related
I am attempting to display data in a textarea, I'm using the
$row=mysqli_fetch_array($results, MYSQLI_NUM)
to extract the record. Using $row[2] displays the correct information using the p function. Using the same syntax with textarea does not display anything. The field is not blank in the database. The code does update the field properly.
I have tried changing to change the textarea to a paragraph with no success. I have change the variable by assigning to a new variable without success. I have tried escaping the column and row quotes all to no effect.
<?php
echo '<input id="title_edit" type="text" name="ppy" value="'.$row[4].'">'
works
echo '<textarea id=prop_edit cols="65" rows="4" type="text" name="ppy" value="'.$row[7].'"></textarea>' does not work.
?>
Should read the field in the database and display it on the screen. But the screen field is blank. There is data in the database.
I'd try:
var_dump($row[2]);
to make sure it actually has the data I want in it.
Since you don't show how the data is being rendered into html I'll guess it is something like this?
echo '<textarea>' . $row[2] . '</textarea>';
If so, check the "view source" option in your browser and double check that it is actually outputting what you expect. If the data in $row[2] contains any interesting characters like < or > or anything that resembles an html tag, you might have to escape the output like this:
echo '<textarea>' . htmlspecialchars($row[2]) . '</textarea>';
I have some custom meta boxes on WordPress, storing some information such as page titles and descriptions, but I am having a bit of a problem which I can't wrap my head around.
The meta input boxes need to be able to accept " and ' (Speech marks and apostrophes), and WordPress is storing the data fine, and I can display it fine on the front end, but when it is echo'd back into the <input> box, it messes up because its trying to print something like this:
E.g: <input value="Hello we're called "example" and we suck" />
So no matter how I go about it, it's being printed in the page edit screen (once I save) like this:
or something to a similar effect. Because I need the use of both characters, I can't use either of them to wrap the attributes in as an easy fix.
I'm just having a bit of a brainfart but really can't figure out the logic behind a solution to solve this, because if I escape the characters, they will just get shown to the end user as Hello we're called "example" and we suck which will confuse them even more.
Encode with esc_attr(), example from the Codex:
echo '<input type="text" name="fname" value="' . esc_attr( $_POST['fname'] ) . '">';
I have a form with a url input that I need to prevent from converting, so that I can use $_GET on the target page. I have tried urlencode, urldecode, html_entity_decode, etc, but none of it prevents the html entity conversion (parse_url did nothing but get rid of all the important stuff). This is the only thread I have found that comes close to what I am trying to achieve.
It seems like there should be a simple solution, and this is not happening anywhere else I am using a url like this...
Thanks to anyone who can help!
echo "<option value='seeArtist.php?aid=".$row[0]."&ac=".$row[1]."&img=".$row[2]."'">
(blah, blah)
<input type="submit" style="margin-left:10px" name="submit" value="Go" />';
This is the result from clicking the submit button.
seeArtist.php?art_con=seeArtist.php%3Faid%3D18%26not%3Bac%3D+(aka)+Banksy%26not%3Bimg%3D0&submit=Go
Two variables are integers, so the database content is not url-encoded.
I suspect that since this is not happening anywhere else, and this is the only place where I am putting a link in a select option, that it has something to do with the submit action. In firebug the link shows up exactly the way it is supposed to. When I submit the url gets encoded.
Regardless of the PHP, your HTML is incorrect. You need to encode the ampersands. Your code should resemble this:
echo "<option value=\"seeArtist.php?aid=" . $row[0] . "&ac=" . $row[1] . "&img=" . $row[2] . "\">\r\n";
I also took the liberty of converting single-quotes to escaped double-quotes.
From a form, I'm asking the user to enter some text. I will retrieve this text using $_POST['text'].
The user enters the string "It's my text!"
$newText = mysql_real_escape_string($_POST['text']);
Now on the very same page after I've inserted $newText into the database I want to display
the text to the user and also use it as the value of an input text box using PHP.
// I want to make sure the user hasn't added any unsafe html in their string
$newText = htmlentities($newText);
echo "You've entered: " . $newText . "<br />";
echo "<form action=someaction.php method=post>";
echo "<input type=text value=\"" . $newText . "\">";
echo "</form>";
The output is:
You've entered: It\'s my text!
[It\'s my text!]
How do I avoid these slashes, and should I be doing anything else with my data?
You're passing the text through mysql_real_escape_string() which, as the name suggests, escapes the string, including apostrophes. mysql_real_escape_string() is meant only for preparing the data for saving to database. You shouldn't use it when displaying data to the user.
So, the solution is simple: remove the line and use htmlentities() only. Use mysql_real_escape_string() when you're saving the string to database (and only then).
Only use mysql_real_escape_string() on the variable you want to use in the query, because it will add slashes to escape some of the characters in the string. This works great for mysql, but when want to use it on the page it will look weird.
You could make 2 variables, 1 for MySQL and 1 for displaying the raw text.
$text = $_POST['text'];
$db_text = mysql_real_escape($text);
Also note that you should use strip_slashes() on the data you get from the database later, to remove the slashes.
Hope this clear things up a little bit.
Now on the very same page after I've inserted $newText into the database I want to display the text to the user
That's what you are doing wrong.
An HTTP standard require a GET method redirect after every successful POST request.
So, you have to redirect the user on the same page, where you may read inserted data from the database and show it to the user.
As for the mistake you made - just move escaping somewhere closer to the database operations, to make sure it is used only for the purpose (YET it is used obligatory, without the risk of forgetting it!).
Ideally you have to use some variables to represent the data in the query, and some handler to process them.
So, the query call may look like
DB::run("UPDATE table SET text=s:text",$_POST['text']);
where s:text is such a variable (called placeholder), which will be substituted with the $_POST['text'] value, properly prepared according to the type set in the placeholder name (s means "string", tells your function to escape and quote the data)
So, all the necessary preparations will be done inside and will spoil no source variable.
save normally using mysql_real_escape_string()
and when you want to display it in a form:
htmlspecialchars(stripslashes($row['text_data']))
it will do the trick.
So, I have a basic little script that takes input from an HTML form, is processes by PHP and then writes it to a text file in the form of CSS. I've already got some jerkwad trying to drop tables on the server (There is no SQL but I'd like to keep people from trying none the less) Here is the code that I have thus far, can someone help me block potentially bad input via htmlentities or something else?
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
<html><body>
<?php
$Friendcode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following information on the server ". $Username . " " . $Usercode . ".<br />"; echo "Thanks for contributing!";
$output = ".author[href\$=\"$Username\"]:after { \n"
."content: \" ($Usercode)\" !important\n"
."}";
}
$fp = fopen('file.txt', 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
</body></html>
You can use htmlentities to convert html tags to their html equiv. < etc. Or you can use strp_tags to get rid of all html tags. If you are using sql use mysql_real_escape_string to make sql queries safer
Whenever you include data entered by the user in HTML code, it is always a good idea to first encode the data, by passing it into htmlspecialchars().
Think of it as a decontamination chamber. This will ensure that any of the HTML special chacters, such as "<" and ">" (deadly viruses) are properly escaped (killed) and won't show up in your page as "real" HTML tags (won't make your webpage sick).
Similarly, you must also encode user input when including it in SQL queries. The function that you use for this purpose varies depending on the database that you are using. Because of the dynamic nature of PHP, if you are a including numeric value in a SQL query, you must first check to make sure the variable contains a number by using functions such as is_numeric() and ctype_digit().
I think the best way to block HTML is to allow only the characters you think a username or a user code may have.
For example, limit the input to letters, numbers and underscores and trim the whitespaces in the beginning and the end of the string. This validation will fail whenever HTML code is provided as input.
I would suggest doing this on both client and server side, with a regex. A client-side example can be found here: jQuery remove all HTML tags EXCEPT Anchors
What happen if someone directly type the url of code.php in browser. They will get the Notice of undefined offset.
You should make at least a check if $_POST is not empty.
if(isset($_POST['submit']) && !empty($_POST))
{
//do operation
}
Validate the user name and user code for special characters and what you allow them to enter with PHP sever side
#Zer0mod: I'd use strip_tags to get rid of HTML and mysql_real_escape_string to take care of any potential SQL injections.
Use PHP to convert every symbol to HTML numbers! Head on over to htmlentities() for details about doing so.