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 )
Related
I want users to have the ability to enter special characters and for it to still submit to the DB.
I have tested using the input: Dave & ' " *, however it doesn't store in the database. If I don't use special characters as per the above and just use Dave, it stores just fine.
I have tried 2 things:
<p class="clearfix">
<label for="name">name</label>
<input class="validate[required]" id="name" name="name" type="text" value="'.esc_attr($_POST['name']).'">
</p>
and
<p class="clearfix">
<label for="name">name</label>
<input class="validate[required]" id="name" name="name" type="text" value="'.htmlspecialchars($_POST['name']).'">
</p>
Neither work.
Database insertion code after payment:
if(strpos($response['body'], 'VERIFIED') !== false && $_POST['payment_status'] == "Completed") {
//Assign IPN Post Values to Local Variables
$comboString = $_POST['txn_id'].$_POST['payment_date'];
$data = explode('~',$_POST['custom']);
$ipn_data = array(
'name' => mysql_real_escape_string($_POST['name']),
'sale_date' => $_POST['payment_date']
);
$ipn_format = array('%s','%s');
if($ipn_business == $paypal_email) {
$wpdb->insert($wpdb->prefix.'orderdata', $ipn_data, $ipn_format);
$ipn_data['currency'] = $_POST['mc_currency'];
$ipn_data['admin_field'] = $_POST['admin_field'];
send_email($ipn_data);
}
} else {
exit("IPN Request Failure");
}
Two very simple rules for this that apply here:
Make strings safe for inserting into a database when, and only when, inserting in to a database
Make strings safe for showing on screen when, and only when, showing on screen.
(Similar rules for adding to XML, adding to URLs / GET paramteters, putting data into email etc - each had a way of handling it.)
So, when instering into a database, use PDO prepared statements or mysqli prepared statements, as this will make the data safe for you. If you can't, then wrap the string in mysql_real_escape_string(). It will NOT change the contents going in (and thus coming out) of the database, just make it safe to enter.
And when displaying on screen, as you have in your second example, use htmlentities() or mysqlspecialchars(). mysqlspecialchars is best if you know how to handle the quotes, but if unsure, use htmlentities.
While I'm at it, I see you're sending an e-mail. Make sure you remove linebreaks and fake boundaries from values that get added to e-mail headers, and remove fake boundaries from the body (line breaks OK). Preferably use a script for email as they are tricky to make spam proof.
When I save this string in PHP:
John: "Yes you can".
In my database is saved as:
John: \
How can I save these strings with " ( without deleting " obviously ).
This is my php code:
$titlepost= mysql_real_escape_string($_POST['title']);
$query = "INSERT INTO `titles` (`title`) VALUES ( '".$titlepost."')";
$res = mysql_query($query) or die("Failed".mysql_error() );
echo $titlepost;
output:
John: \\
FORM:
$title = mysql_real_escape_string($_GET['title']);
<form method="post" action="title.php?done=yes" enctype="multipart/form-data">
<input type="text" size="25" name="title" <?php echo "value=\"".$title."\""; ?> >
<input id="starit" name="submit" value="titleit" type="submit" />
</form>
Your problem has nothing to do with PHP or MysQL.
It is as silly as very simple HTML syntax rule.
It is quite obviously that the code
<input value="John: "YES you can>
will show only quoted "John: " part.
To make it correct, one have to encode special symbols in the value
$titlepost = htmlspecialchars($titlepost,ENT_QUOTES);
?>
<input type="text" name="title" value="<?=$titlepost?>">
As for the slashes - it is silly excessive quoting issue. just quote your strings only once and make sure you have magic_quotes_gpc turned off
If you really just get John: \ in your database, it sounds like you are using magic quotes (that causes you do insert backslashes in the database since you are escaping the escaped string) and the column size is way too small (that's why anything after the backslash is missing).
Try this:
if(get_magic_quotes_gpc()) $_POST = array_map('stripslashes', $_POST);
$titlepost = mysql_real_escape_string($_POST['title']);
This ensures that $_POST does not contain any magic-quotes-escaped data which would break after using mysql_real_escape_string.
Try using prepared statements from PDO
http://php.net/manual/en/pdo.prepared-statements.php
The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).
Here's what I am doing,
<?php
if(isset($_POST['submit'])){
$text_area= mysqli_real_escape_string($dbc, strip_tags(trim($_POST['text_area'])));
echo $text_area;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="textarea" name="text_area" style="width:280px;height:90px" id="myTextarea" />
<input type="submit" name="submit" Value="Submit"/>
</form>
But whenever I try to insert something like this: "Hello World" or 'Hello World', it outputs: \"Hello World\" or \'Hello world\'
where am I going wrong?
That's because you using the mysql-real-escape-string function. Use the stripslashes function on your data before displaying it to remove the slashes.
It seems you are outputting the value from the mysqli_real_escape_string method that escapes the string value for a SQL query to avoid SQL Injection. If you simply want to output anything that was inputted into the textarea then you can just purely show the value from the $_POST array but BEWARE if you don't do any checks you can easily fall victim to someone inputting some javascript etc. and have it appear on the page.
So for example to output just the pure text you sent to the server.
trim($_POST['text_area'])
and then you can call mysqli_real_escape_string again while building your query to make the string safe and avoid some common attacks.
You are using mysqli_real_escape_string incorrectly - it serves no purpose here.
Do not use it in this context, and the problem will go away. Use it only when entering data into a database.
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.
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>